Hytale Server Modding API

Table of Contents

  1. Overview
  2. Event System
  3. Plugin System
  4. Component System (ECS)
  5. Registry System
  6. Server Core APIs
  7. Protocol & Networking
  8. Storage & Persistence
  9. Asset System
  10. Codec & Serialization
  11. Math Library
  12. Procedural Generation
  13. Builtin Modules
  14. Utility Libraries
  15. Metrics & Logging
  16. Function Interfaces
  17. Complete Class Reference

1. Overview

The Hytale Server is built on a sophisticated modular architecture combining:

1.1 Package Structure

com.hypixel.hytale/
├── assetstore/        # Asset loading, registries, and packs (~50 classes)
├── builtin/           # 43 builtin gameplay modules (1,757 classes)
├── codec/             # Serialization framework (165 classes)
├── common/            # Shared utilities (62 classes)
├── component/         # ECS implementation (~100 classes)
├── event/             # Event bus system (23 classes)
├── function/          # Functional interfaces (34 classes)
├── logger/            # Logging framework (17 classes)
├── math/              # Vector/matrix math (95 classes)
├── metrics/           # Performance monitoring (12 classes)
├── plugin/            # Early plugin loader (3 classes)
├── procedurallib/     # Noise & procedural generation (257 classes)
├── protocol/          # Network packets (737 classes)
├── registry/          # Registration framework (3 classes)
├── server/            # Server implementation (3,807 classes)
├── sneakythrow/       # Exception utilities
├── storage/           # Persistence layer (~20 classes)
└── unsafe/            # Low-level utilities

1.2 Key Entry Points

Class Package Description
HytaleServer server Main server class
Universe server.core.universe World container singleton
EventBus event Event system
ComponentRegistry component ECS registry
AssetRegistry assetstore Asset management
CommandManager server.core.command Command system
PacketRegistry protocol Network packets
HytaleLoggerBackend logger.backend Logging backend

2. Event System

Package: com.hypixel.hytale.event Total Files: 23

The event system provides a thread-safe, priority-based event bus supporting both synchronous and asynchronous events.

2.1 Core Interfaces

IBaseEvent\<KeyType>

public interface IBaseEvent<KeyType> {}

Root marker interface for all events. The KeyType generic allows events to be scoped to specific keys.

IEvent\<KeyType>

public interface IEvent<KeyType> extends IBaseEvent<KeyType> {}

Marker interface for synchronous (blocking) events. Handlers execute immediately in priority order.

IAsyncEvent\<KeyType>

public interface IAsyncEvent<KeyType> extends IBaseEvent<KeyType> {}

Marker interface for asynchronous events. Returns CompletableFuture<EventType> for chained async handling.

ICancellable

public interface ICancellable {
    boolean isCancelled();
    void setCancelled(boolean cancelled);
}

Implement this interface to create cancellable events. When cancelled, subsequent handlers may skip processing.

IProcessedEvent

public interface IProcessedEvent {
    void processEvent(@Nonnull String hookName);
}

For events requiring post-dispatch processing with named hooks.

2.2 Event Bus

IEventBus Interface

public interface IEventBus extends IEventRegistry {
    // Synchronous dispatch (no key)
    <KeyType, EventType extends IEvent<KeyType>> EventType dispatch(
        @Nonnull Class<EventType> eventClass);

    // Synchronous dispatch (with key)
    <KeyType, EventType extends IEvent<KeyType>> IEventDispatcher<EventType, EventType>
        dispatchFor(@Nonnull Class<? super EventType> eventClass, @Nullable KeyType key);

    // Asynchronous dispatch (no key)
    <EventType extends IAsyncEvent<Void>> CompletableFuture<EventType> dispatchAsync(
        @Nonnull Class<EventType> eventClass);

    // Asynchronous dispatch (with key)
    <KeyType, EventType extends IAsyncEvent<KeyType>>
        IEventDispatcher<EventType, CompletableFuture<EventType>>
        dispatchForAsync(@Nonnull Class<? super EventType> eventClass, @Nullable KeyType key);
}

EventBus Implementation

public class EventBus implements IEventBus {
    @Nonnull
    private final Map<Class<? extends IBaseEvent<?>>, EventBusRegistry<?, ?, ?>> registryMap;
    private final boolean timeEvents;

    public EventBus(boolean timeEvents);

    public void shutdown();

    @Nonnull
    public Set<Class<? extends IBaseEvent<?>>> getRegisteredEventClasses();

    @Nonnull
    public Set<String> getRegisteredEventClassNames();

    @Nullable
    public EventBusRegistry<?, ?, ?> getRegistry(@Nonnull String eventName);

    @Nonnull
    public <KeyType, EventType extends IBaseEvent<KeyType>> EventBusRegistry<KeyType, EventType, ?>
        getRegistry(@Nonnull Class<? super EventType> eventClass);
}

2.3 Event Registration

IEventRegistry Interface

public interface IEventRegistry {
    // ===== SYNCHRONOUS REGISTRATION (6 overloads) =====

    // Basic registration (default priority)
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        register(Class<EventType> eventClass, Consumer<EventType> handler);

    // With EventPriority enum
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        register(EventPriority priority, Class<EventType> eventClass, Consumer<EventType> handler);

    // With raw priority value
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        register(short priority, Class<EventType> eventClass, Consumer<EventType> handler);

    // With key (default priority)
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        register(Class<EventType> eventClass, KeyType key, Consumer<EventType> handler);

    // With key and EventPriority
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        register(EventPriority priority, Class<EventType> eventClass, KeyType key, Consumer<EventType> handler);

    // With key and raw priority
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        register(short priority, Class<EventType> eventClass, KeyType key, Consumer<EventType> handler);

    // ===== ASYNCHRONOUS REGISTRATION (6 overloads) =====

    @Nullable
    <KeyType, EventType extends IAsyncEvent<KeyType>> EventRegistration<KeyType, EventType>
        registerAsync(Class<EventType> eventClass,
            Function<CompletableFuture<EventType>, CompletableFuture<EventType>> handler);

    // ... (same pattern as sync with priority and key variants)

    // ===== GLOBAL REGISTRATION (all keys) =====
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        registerGlobal(Class<EventType> eventClass, Consumer<EventType> handler);

    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        registerGlobal(EventPriority priority, Class<EventType> eventClass, Consumer<EventType> handler);

    // ===== UNHANDLED FALLBACK REGISTRATION =====
    @Nullable
    <KeyType, EventType extends IEvent<KeyType>> EventRegistration<KeyType, EventType>
        registerUnhandled(Class<EventType> eventClass, Consumer<EventType> handler);
}

EventRegistration

public class EventRegistration<KeyType, EventType extends IBaseEvent<KeyType>>
    extends Registration {

    @Nonnull
    protected final Class<EventType> eventClass;

    public EventRegistration(
        @Nonnull Class<EventType> eventClass,
        @Nonnull BooleanSupplier isEnabled,
        @Nonnull Runnable unregister);

    public EventRegistration(
        @Nonnull EventRegistration<KeyType, EventType> registration,
        @Nonnull BooleanSupplier isEnabled,
        @Nonnull Runnable unregister);

    @Nonnull
    public Class<EventType> getEventClass();

    @Nonnull
    @Override
    public String toString();

    @Nonnull
    @SafeVarargs
    public static <KeyType, EventType extends IBaseEvent<KeyType>>
        EventRegistration<KeyType, EventType> combine(
            @Nonnull EventRegistration<KeyType, EventType> first,
            @Nonnull EventRegistration<KeyType, EventType>... others);
}

2.4 Event Priority

Priority determines handler execution order (ascending). Lower values execute first.

public enum EventPriority {
    // Values range from -32768 to 32767 (short)
    // Default priority is 0

    public short getValue();
}

Usage Examples:

// Using enum
eventBus.register(EventPriority.HIGH, MyEvent.class, handler);

// Using raw priority values
eventBus.register((short) -100, MyEvent.class, handler);  // Execute early
eventBus.register((short) 100, MyEvent.class, handler);   // Execute late

2.5 Event Dispatcher

public interface IEventDispatcher<EventType extends IBaseEvent, ReturnType> {
    default boolean hasListener() {
        return true;
    }

    ReturnType dispatch(@Nullable EventType event);
}

2.6 Usage Examples

Registering a Synchronous Handler

IEventBus eventBus = server.getEventBus();

// Simple registration (default priority)
eventBus.register(PlayerJoinEvent.class, event -> {
    Player player = event.getPlayer();
    player.sendMessage("Welcome!");
});

// With priority (executes before normal handlers)
eventBus.register(EventPriority.HIGH, PlayerJoinEvent.class, event -> {
    // Early processing
});

// Key-scoped registration (only for specific key)
eventBus.register(BlockBreakEvent.class, specificBlockType, event -> {
    // Only handles events for specificBlockType
});

// Global registration (receives all keys)
eventBus.registerGlobal(BlockBreakEvent.class, event -> {
    // Handles all block break events regardless of block type
});

Registering an Async Handler

eventBus.registerAsync(AsyncDataLoadEvent.class, future -> {
    return future.thenApply(event -> {
        // Process asynchronously
        loadDataFromDatabase(event);
        return event;
    });
});

Dispatching Events

// Synchronous dispatch (simple)
PlayerJoinEvent event = eventBus.dispatch(PlayerJoinEvent.class);

// With custom event instance via dispatcher
IEventDispatcher<PlayerJoinEvent, PlayerJoinEvent> dispatcher =
    eventBus.dispatchFor(PlayerJoinEvent.class, null);
PlayerJoinEvent result = dispatcher.dispatch(new PlayerJoinEvent(player));

// Asynchronous dispatch
CompletableFuture<AsyncEvent> future = eventBus.dispatchAsync(AsyncEvent.class);
future.thenAccept(event -> handleResult(event));

// Check if dispatcher has listeners before creating expensive event
IEventDispatcher<ExpensiveEvent, ExpensiveEvent> expensiveDispatcher =
    eventBus.dispatchFor(ExpensiveEvent.class, null);
if (expensiveDispatcher.hasListener()) {
    expensiveDispatcher.dispatch(createExpensiveEvent());
}

Creating Cancellable Events

public class BlockBreakEvent implements IEvent<BlockType>, ICancellable {
    private final Player player;
    private final BlockType blockType;
    private final Vector3i position;
    private boolean cancelled = false;

    public BlockBreakEvent(Player player, BlockType blockType, Vector3i position) {
        this.player = player;
        this.blockType = blockType;
        this.position = position;
    }

    @Override
    public boolean isCancelled() {
        return cancelled;
    }

    @Override
    public void setCancelled(boolean cancelled) {
        this.cancelled = cancelled;
    }

    public Player getPlayer() { return player; }
    public BlockType getBlockType() { return blockType; }
    public Vector3i getPosition() { return position; }
}

// Handler that cancels the event
eventBus.register(BlockBreakEvent.class, event -> {
    if (isProtectedBlock(event.getPosition())) {
        event.setCancelled(true);
        event.getPlayer().sendMessage("You cannot break this block!");
    }
});

Unregistering Events

// Store the registration
EventRegistration<?, ?> registration = eventBus.register(MyEvent.class, handler);

// Later, unregister
registration.unregister();

// Check if still registered
if (registration.isRegistered()) {
    // Still active
}

2.7 Internal Architecture

EventBusRegistry

Abstract base for sync/async registries with priority-based consumer storage.

public abstract class EventBusRegistry<KeyType, EventType extends IBaseEvent<KeyType>,
    ConsumerMapType extends EventBusRegistry.EventConsumerMap<...>> {

    @Nonnull
    protected static final Object NULL = new Object();  // Sentinel for null keys

    @Nonnull
    protected final HytaleLogger logger;

    @Nonnull
    protected final Class<EventType> eventClass;

    @Nonnull
    protected final Map<KeyType, ConsumerMapType> map;  // ConcurrentHashMap

    @Nonnull
    protected final ConsumerMapType global;  // Global handlers

    @Nonnull
    protected final ConsumerMapType unhandled;  // Fallback handlers

    protected boolean timeEvents;
    protected boolean shutdown;

    @Nonnull
    public Class<EventType> getEventClass();

    public boolean isTimeEvents();
    public void setTimeEvents(boolean timeEvents);

    public void shutdown();
    public boolean isAlive();

    public abstract EventRegistration<KeyType, EventType> register(
        short priority, @Nullable KeyType key, @Nonnull Consumer<EventType> consumer);

    public abstract EventRegistration<KeyType, EventType> registerGlobal(
        short priority, @Nonnull Consumer<EventType> consumer);

    public abstract EventRegistration<KeyType, EventType> registerUnhandled(
        short priority, @Nonnull Consumer<EventType> consumer);

    public abstract IEventDispatcher<EventType, ?> dispatchFor(KeyType key);
}

EventConsumer

Base class wrapping event handlers with timing metrics.

public static abstract class EventConsumer {
    @Nonnull
    protected static final AtomicInteger consumerIndex = new AtomicInteger();

    protected final int index;           // Unique consumer ID
    protected final short priority;      // Execution priority

    @Nonnull
    protected final String consumerString;  // Handler description

    @Nonnull
    protected final Metric timer = new Metric();  // Performance tracking

    public EventConsumer(short priority, @Nonnull String consumerString);

    public int getIndex();
    public short getPriority();

    @Nonnull
    public String getConsumerString();

    @Nonnull
    public Metric getTimer();
}

EventConsumerMap

Priority-sorted consumer storage using Short2ObjectConcurrentHashMap.

public static abstract class EventConsumerMap<EventType extends IBaseEvent,
    ConsumerType extends EventBusRegistry.EventConsumer, ReturnType>
    implements IEventDispatcher<EventType, ReturnType> {

    private static final short[] EMPTY_SHORT_ARRAY = new short[0];

    private final AtomicReference<short[]> prioritiesRef =
        new AtomicReference<>(EMPTY_SHORT_ARRAY);

    @Nonnull
    private final Short2ObjectConcurrentHashMap<List<ConsumerType>> map =
        new Short2ObjectConcurrentHashMap(true, -32768);

    public boolean isEmpty();

    public void add(@Nonnull ConsumerType eventConsumer);
    public boolean remove(@Nonnull ConsumerType consumer);

    public short[] getPriorities();

    @Nullable
    public List<ConsumerType> get(short priority);
}

SyncEventConsumer

public class SyncEventConsumer<EventType extends IEvent>
    extends EventBusRegistry.EventConsumer {

    @Nonnull
    private final Consumer<EventType> consumer;

    @Nonnull
    private final Consumer<EventType> timedConsumer;

    public SyncEventConsumer(short priority, @Nonnull Consumer<EventType> consumer);

    @Nonnull
    protected Consumer<EventType> getConsumer();

    @Nonnull
    public Consumer<EventType> getTimedConsumer();
}

AsyncEventConsumer

public class AsyncEventConsumer<EventType extends IAsyncEvent>
    extends EventBusRegistry.EventConsumer {

    @Nonnull
    private final Function<CompletableFuture<EventType>, CompletableFuture<EventType>> function;

    @Nonnull
    private final Function<CompletableFuture<EventType>, CompletableFuture<EventType>> timedFunction;

    public AsyncEventConsumer(
        short priority,
        @Nonnull String consumerString,
        @Nonnull Function<CompletableFuture<EventType>, CompletableFuture<EventType>> function);

    @Nonnull
    public Function<CompletableFuture<EventType>, CompletableFuture<EventType>> getFunction();

    @Nonnull
    public Function<CompletableFuture<EventType>, CompletableFuture<EventType>> getTimedFunction();
}

2.8 Thread Safety

The event system is fully thread-safe:

2.9 Performance Features


3. Plugin System

Package: com.hypixel.hytale.plugin.early Total Files: 3

The plugin system provides bytecode transformation capabilities via Java's ServiceLoader mechanism.

3.1 ClassTransformer Interface

package com.hypixel.hytale.plugin.early;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public interface ClassTransformer {
    /**
     * Returns the priority of this transformer.
     * Higher values execute first (descending order).
     *
     * @return priority (default: 0)
     */
    default int priority() {
        return 0;
    }

    /**
     * Transform class bytecode.
     *
     * @param className Binary class name (e.g., "com.hypixel.MyClass")
     * @param internalName Internal name (e.g., "com/hypixel/MyClass")
     * @param classBytes Original bytecode
     * @return Transformed bytecode, or null to skip transformation
     */
    @Nullable
    byte[] transform(
        @Nonnull String className,
        @Nonnull String internalName,
        @Nonnull byte[] classBytes);
}

3.2 EarlyPluginLoader

package com.hypixel.hytale.plugin.early;

import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.List;

public final class EarlyPluginLoader {
    /**
     * Default plugin directory.
     */
    public static final Path EARLY_PLUGINS_PATH = Path.of("earlyplugins");

    /**
     * Static list of loaded transformers.
     */
    private static final List<ClassTransformer> transformers;

    /**
     * ClassLoader for plugin classes.
     */
    @Nullable
    private static URLClassLoader pluginClassLoader;

    /**
     * Loads early plugins from the default directory and command-line paths.
     *
     * Process:
     * 1. Collects JARs from earlyplugins/
     * 2. Collects JARs from --early-plugins paths
     * 3. Creates URLClassLoader with discovered JARs
     * 4. Uses ServiceLoader to find ClassTransformer implementations
     * 5. Sorts transformers by priority (descending)
     * 6. Requires user confirmation (unless --singleplayer or --accept-early-plugins)
     *
     * @param args Command-line arguments
     */
    public static void loadEarlyPlugins(String[] args);

    /**
     * @return true if any transformers are loaded
     */
    public static boolean hasTransformers();

    /**
     * @return Unmodifiable list of loaded transformers
     */
    public static List<ClassTransformer> getTransformers();

    /**
     * @return The plugin ClassLoader, or null if not initialized
     */
    @Nullable
    public static URLClassLoader getPluginClassLoader();
}

Command-Line Arguments

Argument Type Description
--early-plugins=path1,path2,... Optional Additional plugin directories (comma-separated)
--early-plugins path1,path2,... Optional Alternative syntax for plugin directories
--singleplayer Flag Skip transformer confirmation prompt
--accept-early-plugins Flag Accept transformer risks without prompt

3.3 TransformingClassLoader

Custom ClassLoader that applies transformers to loaded classes.

package com.hypixel.hytale.plugin.early;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;

public final class TransformingClassLoader extends URLClassLoader {
    /**
     * Protected packages that cannot be transformed (security boundary).
     */
    private static final Set<String> SECURE_PACKAGE_PREFIXES = Set.of(
        "java.",
        "javax.",
        "jdk.",
        "sun.",
        "com.sun.",
        "org.bouncycastle.",
        "server.io.netty.",
        "org.objectweb.asm.",
        "com.google.gson.",
        "org.slf4j.",
        "org.apache.logging.",
        "ch.qos.logback.",
        "com.google.flogger.",
        "server.io.sentry.",
        "com.hypixel.protoplus.",
        "com.hypixel.fastutil.",
        "com.hypixel.hytale.plugin.early."
    );

    @Nonnull
    private final List<ClassTransformer> transformers;

    @Nonnull
    private final ClassLoader appClassLoader;

    /**
     * @param urls Plugin JAR URLs
     * @param transformers Transformers to apply
     * @param parent Parent ClassLoader
     * @param appClassLoader App's original ClassLoader for secure classes
     */
    public TransformingClassLoader(
        @Nonnull URL[] urls,
        @Nonnull List<ClassTransformer> transformers,
        ClassLoader parent,
        ClassLoader appClassLoader);

    /**
     * Loads a class, applying transformers if not a secure package.
     *
     * Process:
     * 1. Check if already loaded (cache)
     * 2. If preloaded class → delegate to appClassLoader
     * 3. If in plugin JARs → transform bytecode
     * 4. Otherwise → delegate to parent
     *
     * @param name Binary class name
     * @param resolve Whether to resolve the class
     * @return Loaded class
     * @throws ClassNotFoundException if class not found
     */
    @Override
    protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException;
}

Preloaded Classes

Classes that bypass transformation and load from appClassLoader: - com.hypixel.hytale.Main - All classes in com.hypixel.hytale.plugin.early.*

3.4 Creating a Plugin

Step 1: Implement ClassTransformer

package com.mymod;

import com.hypixel.hytale.plugin.early.ClassTransformer;
import org.objectweb.asm.*;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class MyTransformer implements ClassTransformer {

    @Override
    public int priority() {
        return 100;  // Higher = executed first
    }

    @Nullable
    @Override
    public byte[] transform(
            @Nonnull String className,
            @Nonnull String internalName,
            @Nonnull byte[] classBytes) {

        // Only transform specific classes
        if (!className.equals("com.hypixel.hytale.server.SomeClass")) {
            return null;  // No transformation
        }

        // Use ASM to transform bytecode
        ClassReader reader = new ClassReader(classBytes);
        ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES);

        ClassVisitor visitor = new ClassVisitor(Opcodes.ASM9, writer) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor,
                                            String signature, String[] exceptions) {
                MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);

                if (name.equals("targetMethod")) {
                    return new MethodVisitor(Opcodes.ASM9, mv) {
                        @Override
                        public void visitCode() {
                            super.visitCode();
                            // Add code at method start
                            mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out",
                                            "Ljava/io/PrintStream;");
                            mv.visitLdcInsn("Method called!");
                            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream",
                                             "println", "(Ljava/lang/String;)V", false);
                        }
                    };
                }
                return mv;
            }
        };

        reader.accept(visitor, 0);
        return writer.toByteArray();
    }
}

Step 2: Register via ServiceLoader

Create file: META-INF/services/com.hypixel.hytale.plugin.early.ClassTransformer

com.mymod.MyTransformer

Step 3: Create manifest.json (Optional)

{
    "group": "com.mymod",
    "name": "MyMod",
    "version": "1.0.0",
    "description": "My awesome mod",
    "authors": [
        {
            "name": "MyName",
            "email": "me@example.com"
        }
    ],
    "main": "com.mymod.MyTransformer"
}

Step 4: Build and Deploy

<!-- pom.xml -->
<project>
    <groupId>com.mymod</groupId>
    <artifactId>mymod</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>9.5</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>META-INF/services/**</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

Build the JAR and place it in the earlyplugins/ directory.

3.5 Security Considerations

  1. Bytecode Transformation Risks
  2. Transformers can modify any non-secure class
  3. Marked as "unsupported and may cause stability issues"
  4. Requires user confirmation in interactive mode

  5. Protected Packages

  6. Core Java packages cannot be transformed
  7. Server infrastructure packages protected
  8. Plugin system itself protected

  9. Console Safety

  10. If no console available and confirmation needed → exits with code 1
  11. Prevents headless systems from accidentally accepting transformers

3.6 Logging

[EarlyPlugin] Found: my-mod.jar
[EarlyPlugin] Loading transformer: com.mymod.MyTransformer (priority=100)

4. Component System (ECS)

Package: com.hypixel.hytale.component Total Files: ~100

The Hytale server uses a sophisticated Entity Component System (ECS) with archetype-based storage for optimal cache performance.

4.1 Core Concepts

Concept Description
Entity A unique ID represented by Ref<ECS_TYPE>
Component Data attached to entities (implements Component<ECS_TYPE>)
Resource Global singleton data (implements Resource<ECS_TYPE>)
System Logic operating on entities with specific components
Archetype Set of component types defining entity structure
Store Container managing all entities and components
Holder Entity template before instantiation
Query Predicate for filtering entities by components
CommandBuffer Deferred command execution for safe modifications

4.2 Component Interface

package com.hypixel.hytale.component;

import javax.annotation.Nullable;

public interface Component<ECS_TYPE> extends Cloneable {
    /**
     * Clone this component.
     * @return Cloned component, or null if not cloneable
     */
    @Nullable
    Component<ECS_TYPE> clone();

    /**
     * Clone for serialization purposes.
     * Default implementation delegates to clone().
     * @return Cloned component suitable for serialization
     */
    @Nullable
    default Component<ECS_TYPE> cloneSerializable() {
        return clone();
    }
}

Special Marker Components

/**
 * Marker component that prevents serialization.
 * Add to entities that should not be persisted.
 */
public final class NonSerialized<ECS_TYPE> implements Component<ECS_TYPE> {
    public static final NonSerialized<?> INSTANCE = new NonSerialized<>();

    @Override
    public Component<ECS_TYPE> clone() {
        return this;  // Singleton
    }
}

/**
 * Marker component that prevents ticking.
 * Add to entities that should not be processed by ticking systems.
 */
public final class NonTicking<ECS_TYPE> implements Component<ECS_TYPE> {
    public static final NonTicking<?> INSTANCE = new NonTicking<>();

    @Override
    public Component<ECS_TYPE> clone() {
        return this;  // Singleton
    }
}

4.3 Resource Interface

package com.hypixel.hytale.component;

import javax.annotation.Nullable;

/**
 * Global singleton resource accessible throughout the ECS.
 * Unlike components, resources are not attached to entities.
 */
public interface Resource<ECS_TYPE> extends Cloneable {
    /**
     * Clone this resource.
     * @return Cloned resource, or null if not cloneable
     */
    @Nullable
    Resource<ECS_TYPE> clone();
}

4.4 Entity Reference (Ref)

package com.hypixel.hytale.component;

/**
 * Opaque reference to an entity.
 * Safe handle that detects invalid references when entity is deleted.
 */
public class Ref<ECS_TYPE> {
    private final Store<ECS_TYPE> store;
    private volatile int index;
    private volatile int hashCode;
    private volatile Throwable invalidatedBy;

    /**
     * @return The store containing this entity
     */
    public Store<ECS_TYPE> getStore();

    /**
     * @return The entity index in the store
     */
    public int getIndex();

    /**
     * @return true if this reference is still valid
     */
    public boolean isValid();

    /**
     * Validates this reference.
     * @throws IllegalStateException if reference is invalid
     */
    public void validate() throws IllegalStateException;

    /**
     * Marks this reference as invalid (entity deleted).
     */
    public void invalidate();
}

4.5 Entity Holder

package com.hypixel.hytale.component;

import java.util.concurrent.locks.StampedLock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Entity data template before adding to store.
 * Thread-safe with StampedLock for concurrent access.
 */
public class Holder<ECS_TYPE> {
    private final StampedLock lock = new StampedLock();
    private Archetype<ECS_TYPE> archetype;
    private Component<ECS_TYPE>[] components;
    private boolean ensureValidComponents = true;

    /**
     * Create holder with a component.
     * @param type Component type
     * @param component Component instance
     * @return this holder for chaining
     */
    @Nonnull
    public <T extends Component<ECS_TYPE>> Holder<ECS_TYPE> with(
        ComponentType<ECS_TYPE, T> type, T component);

    /**
     * Get component from holder.
     * @param type Component type
     * @return Component instance, or null if not present
     */
    @Nullable
    public <T extends Component<ECS_TYPE>> T get(ComponentType<ECS_TYPE, T> type);

    /**
     * @return The archetype of this holder
     */
    @Nonnull
    public Archetype<ECS_TYPE> getArchetype();
}

4.6 Store (Main ECS Container)

package com.hypixel.hytale.component;

import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Main ECS container managing all entities, components, and resources.
 * Thread-safe and optimized for high-performance entity processing.
 */
public class Store<ECS_TYPE> implements ComponentAccessor<ECS_TYPE> {
    private final ComponentRegistry<ECS_TYPE> registry;
    private final ECS_TYPE externalData;
    private final IResourceStorage resourceStorage;

    // ===== ENTITY MANAGEMENT =====

    /**
     * Add entity from holder.
     * @param holder Entity template
     * @return Reference to new entity
     */
    @Nonnull
    public Ref<ECS_TYPE> addEntity(Holder<ECS_TYPE> holder);

    /**
     * Add entity with reason.
     * @param holder Entity template
     * @param reason Why entity is being added
     * @return Reference to new entity
     */
    @Nonnull
    public Ref<ECS_TYPE> addEntity(Holder<ECS_TYPE> holder, AddReason reason);

    /**
     * Add multiple entities.
     * @param holders Entity templates
     * @param reason Why entities are being added
     * @return References to new entities
     */
    @Nonnull
    public Ref<ECS_TYPE>[] addEntities(Holder<ECS_TYPE>[] holders, AddReason reason);

    /**
     * Remove entity from store.
     * @param ref Entity reference
     * @param reason Why entity is being removed
     * @return Holder containing entity's components (for potential transfer)
     */
    @Nullable
    public Holder<ECS_TYPE> removeEntity(Ref<ECS_TYPE> ref, RemoveReason reason);

    // ===== COMPONENT ACCESS =====

    /**
     * Get component from entity.
     * @param ref Entity reference
     * @param type Component type
     * @return Component instance, or null if not present
     */
    @Nullable
    @Override
    public <T extends Component<ECS_TYPE>> T getComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type);

    /**
     * Get component, creating default if not present.
     * @param ref Entity reference
     * @param type Component type
     * @return Component instance (never null)
     */
    @Nonnull
    @Override
    public <T extends Component<ECS_TYPE>> T ensureAndGetComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type);

    /**
     * Set component on entity (replaces existing).
     * @param ref Entity reference
     * @param type Component type
     * @param value Component instance
     */
    @Override
    public <T extends Component<ECS_TYPE>> void putComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type, T value);

    /**
     * Add component to entity.
     * @param ref Entity reference
     * @param type Component type
     * @param value Component instance
     */
    @Override
    public <T extends Component<ECS_TYPE>> void addComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type, T value);

    /**
     * Add component using default supplier.
     * @param ref Entity reference
     * @param type Component type
     * @return Created component
     */
    @Nonnull
    @Override
    public <T extends Component<ECS_TYPE>> T addComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type);

    /**
     * Remove component from entity.
     * @param ref Entity reference
     * @param type Component type
     */
    @Override
    public <T extends Component<ECS_TYPE>> void removeComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type);

    /**
     * Try to remove component (no error if not present).
     * @param ref Entity reference
     * @param type Component type
     */
    @Override
    public <T extends Component<ECS_TYPE>> void tryRemoveComponent(
        Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type);

    // ===== RESOURCE ACCESS =====

    /**
     * Get global resource.
     * @param type Resource type
     * @return Resource instance
     */
    @Override
    public <T extends Resource<ECS_TYPE>> T getResource(ResourceType<ECS_TYPE, T> type);

    /**
     * @return External data associated with this store
     */
    @Override
    public ECS_TYPE getExternalData();

    // ===== ARCHETYPE =====

    /**
     * Get entity's archetype.
     * @param ref Entity reference
     * @return Archetype describing entity's components
     */
    @Override
    public Archetype<ECS_TYPE> getArchetype(Ref<ECS_TYPE> ref);

    // ===== EVENTS =====

    /**
     * Invoke event on entity.
     * @param ref Target entity
     * @param event Event instance
     */
    @Override
    public <Event extends EcsEvent> void invoke(Ref<ECS_TYPE> ref, Event event);

    /**
     * Invoke entity event with explicit type.
     * @param type Event type
     * @param ref Target entity
     * @param event Event instance
     */
    @Override
    public <Event extends EcsEvent> void invoke(
        EntityEventType<ECS_TYPE, Event> type, Ref<ECS_TYPE> ref, Event event);

    /**
     * Invoke world-wide event.
     * @param event Event instance
     */
    @Override
    public <Event extends EcsEvent> void invoke(Event event);

    /**
     * Invoke world event with explicit type.
     * @param type Event type
     * @param event Event instance
     */
    @Override
    public <Event extends EcsEvent> void invoke(
        WorldEventType<ECS_TYPE, Event> type, Event event);

    // ===== COMMAND BUFFER =====

    /**
     * Create command buffer for deferred operations.
     * Useful during iteration to avoid concurrent modification.
     * @return New command buffer
     */
    @Nonnull
    public CommandBuffer<ECS_TYPE> fork();

    // ===== SYSTEM TICK =====

    /**
     * Execute all registered systems.
     * Called each game tick.
     */
    public void tick();
}

4.7 Archetype

package com.hypixel.hytale.component;

import javax.annotation.Nonnull;

/**
 * Represents a specific combination of component types.
 * Immutable snapshot used for entity categorization and queries.
 */
public class Archetype<ECS_TYPE> implements Query<ECS_TYPE> {
    private final int minIndex;
    private final int count;
    private final ComponentType<ECS_TYPE, ?>[] componentTypes;

    /**
     * @return Empty archetype singleton
     */
    @Nonnull
    public static <ECS_TYPE> Archetype<ECS_TYPE> empty();

    /**
     * @return Minimum component index in this archetype
     */
    public int getMinIndex();

    /**
     * @return Number of components in this archetype
     */
    public int count();

    /**
     * @return Array length (may be larger than count for sparse storage)
     */
    public int length();

    /**
     * Get component type by index.
     * @param index Component index
     * @return Component type at index
     */
    public ComponentType<ECS_TYPE, ?> get(int index);

    @Override
    public boolean test(Archetype<ECS_TYPE> archetype) {
        // Tests if this archetype matches the query
        return true;
    }
}

4.8 ArchetypeChunk

Dense storage for entities with the same archetype (Struct-of-Arrays layout).

package com.hypixel.hytale.component;

import javax.annotation.Nonnull;

/**
 * Cache-efficient storage for entities sharing the same archetype.
 * Uses Struct-of-Arrays (SoA) layout for optimal memory access patterns.
 */
public class ArchetypeChunk<ECS_TYPE> {
    protected final Store<ECS_TYPE> store;
    protected final Archetype<ECS_TYPE> archetype;
    protected int entitiesSize;
    protected Ref<ECS_TYPE>[] refs;           // Entity references
    protected Component<ECS_TYPE>[][] components;  // [componentIndex][entityIndex]

    /**
     * @return Archetype shared by all entities in this chunk
     */
    @Nonnull
    public Archetype<ECS_TYPE> getArchetype();

    /**
     * @return Number of entities in this chunk
     */
    public int size();

    /**
     * Convert to holder for serialization.
     * @return Holder containing chunk data
     */
    @Nonnull
    public Holder<ECS_TYPE> toHolder();
}

4.9 Component Registry

package com.hypixel.hytale.component;

import java.util.function.Supplier;
import javax.annotation.Nonnull;

/**
 * Central registry for components, resources, systems, and events.
 * Thread-safe with StampedLock for concurrent registration.
 */
public interface IComponentRegistry<ECS_TYPE> {

    // ===== COMPONENT REGISTRATION =====

    /**
     * Register component type with supplier.
     * @param clazz Component class
     * @param supplier Factory for creating instances
     * @return Component type handle
     */
    @Nonnull
    <T extends Component<ECS_TYPE>> ComponentType<ECS_TYPE, T>
        registerComponent(Class<? super T> clazz, Supplier<T> supplier);

    /**
     * Register component type with codec (for serialization).
     * @param clazz Component class
     * @param id Serialization ID
     * @param codec Serialization codec
     * @return Component type handle
     */
    @Nonnull
    <T extends Component<ECS_TYPE>> ComponentType<ECS_TYPE, T>
        registerComponent(Class<? super T> clazz, String id, BuilderCodec<T> codec);

    // ===== RESOURCE REGISTRATION =====

    /**
     * Register resource type with supplier.
     * @param clazz Resource class
     * @param supplier Factory for creating instances
     * @return Resource type handle
     */
    @Nonnull
    <T extends Resource<ECS_TYPE>> ResourceType<ECS_TYPE, T>
        registerResource(Class<? super T> clazz, Supplier<T> supplier);

    // ===== SYSTEM REGISTRATION =====

    /**
     * Register system type.
     * @param clazz System class
     * @return System type handle
     */
    @Nonnull
    <T extends ISystem<ECS_TYPE>> SystemType<ECS_TYPE, T>
        registerSystemType(Class<? super T> clazz);

    /**
     * Register system instance.
     * @param system System to register
     */
    void registerSystem(ISystem<ECS_TYPE> system);

    // ===== EVENT REGISTRATION =====

    /**
     * Register entity-targeted event type.
     * @param clazz Event class
     * @return Event type handle
     */
    @Nonnull
    <T extends EcsEvent> EntityEventType<ECS_TYPE, T>
        registerEntityEventType(Class<? super T> clazz);

    /**
     * Register world-wide event type.
     * @param clazz Event class
     * @return Event type handle
     */
    @Nonnull
    <T extends EcsEvent> WorldEventType<ECS_TYPE, T>
        registerWorldEventType(Class<? super T> clazz);

    // ===== SYSTEM GROUP REGISTRATION =====

    /**
     * Register system group for ordering.
     * @return System group handle
     */
    @Nonnull
    SystemGroup<ECS_TYPE> registerSystemGroup();

    // ===== SPATIAL REGISTRATION =====

    /**
     * Register spatial resource for spatial queries.
     * @param supplier Factory for spatial structure
     * @return Resource type handle
     */
    @Nonnull
    ResourceType<ECS_TYPE, SpatialResource<Ref<ECS_TYPE>, ECS_TYPE>>
        registerSpatialResource(Supplier<SpatialStructure<Ref<ECS_TYPE>>> supplier);
}

4.10 System Types

Base System Interface

package com.hypixel.hytale.component.system;

import java.util.Set;
import javax.annotation.Nullable;

/**
 * Base interface for all ECS systems.
 */
public interface ISystem<ECS_TYPE> {
    /**
     * Called when system is registered.
     */
    default void onSystemRegistered() {}

    /**
     * Called when system is unregistered.
     */
    default void onSystemUnregistered() {}

    /**
     * @return System group for ordering, or null for default
     */
    @Nullable
    default SystemGroup<ECS_TYPE> getGroup() {
        return null;
    }

    /**
     * @return Dependencies for ordering
     */
    default Set<Dependency<ECS_TYPE>> getDependencies() {
        return Set.of();
    }

    /**
     * Calculate system execution order.
     * @param registry Component registry
     * @param systems Systems to order
     * @param systemSize Number of systems
     */
    static <ECS_TYPE> void calculateOrder(
        ComponentRegistry<ECS_TYPE> registry,
        ISystem<ECS_TYPE>[] systems,
        int systemSize);
}

System Abstract Class

package com.hypixel.hytale.component.system;

import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Base class for systems with component/resource registration helpers.
 */
public abstract class System<ECS_TYPE> implements ISystem<ECS_TYPE> {
    /**
     * Register component during system setup.
     * @param clazz Component class
     * @param id Serialization ID
     * @param codec Serialization codec
     * @param supplier Factory
     * @return Component type handle
     */
    protected <T extends Component<ECS_TYPE>> ComponentType<ECS_TYPE, T>
        registerComponent(
            Class<? super T> clazz,
            @Nullable String id,
            @Nullable BuilderCodec<T> codec,
            Supplier<T> supplier);

    /**
     * Register resource during system setup.
     */
    public <T extends Resource<ECS_TYPE>> ResourceType<ECS_TYPE, T>
        registerResource(
            Class<? super T> clazz,
            @Nullable String id,
            @Nullable BuilderCodec<T> codec,
            Supplier<T> supplier);
}

Query System

package com.hypixel.hytale.component.system;

/**
 * System that filters entities by query.
 */
public interface QuerySystem<ECS_TYPE> extends ISystem<ECS_TYPE> {
    /**
     * Test if archetype matches this system's query.
     * @param registry Component registry
     * @param archetype Archetype to test
     * @return true if archetype matches
     */
    default boolean test(ComponentRegistry<ECS_TYPE> registry, Archetype<ECS_TYPE> archetype) {
        return getQuery().test(archetype);
    }

    /**
     * @return Query defining which entities this system processes
     */
    @Nonnull
    Query<ECS_TYPE> getQuery();
}

Ticking Systems

package com.hypixel.hytale.component.system.tick;

/**
 * System that executes each tick.
 */
public abstract class TickingSystem<ECS_TYPE> extends System<ECS_TYPE>
    implements TickableSystem<ECS_TYPE> {

    /**
     * Called each tick.
     * @param dt Delta time since last tick
     * @param systemIndex This system's index
     * @param store Store to process
     */
    abstract void tick(float dt, int systemIndex, Store<ECS_TYPE> store);
}

/**
 * Ticking system that processes archetype chunks.
 */
public abstract class ArchetypeTickingSystem<ECS_TYPE> extends TickingSystem<ECS_TYPE>
    implements QuerySystem<ECS_TYPE> {

    /**
     * Process one archetype chunk.
     * @param dt Delta time
     * @param chunk Chunk to process
     * @param store Parent store
     * @param buffer Command buffer for deferred operations
     */
    abstract void tick(
        float dt,
        ArchetypeChunk<ECS_TYPE> chunk,
        Store<ECS_TYPE> store,
        CommandBuffer<ECS_TYPE> buffer);
}

/**
 * Ticking system with per-entity iteration and parallelization support.
 */
public abstract class EntityTickingSystem<ECS_TYPE>
    extends ArchetypeTickingSystem<ECS_TYPE> {

    /**
     * Process one entity.
     * @param dt Delta time
     * @param index Entity index in chunk
     * @param chunk Containing chunk
     * @param store Parent store
     * @param buffer Command buffer
     */
    abstract void tick(
        float dt,
        int index,
        ArchetypeChunk<ECS_TYPE> chunk,
        Store<ECS_TYPE> store,
        CommandBuffer<ECS_TYPE> buffer);

    /**
     * Helper for parallel entity processing.
     */
    static <ECS_TYPE> void doTick(
        EntityTickingSystem<ECS_TYPE> system,
        float dt,
        ArchetypeChunk<ECS_TYPE> chunk,
        Store<ECS_TYPE> store,
        CommandBuffer<ECS_TYPE> buffer);

    /**
     * Task data for parallel processing.
     */
    static class SystemTaskData<ECS_TYPE> implements IntConsumer {
        // Distributes work across parallel tasks
    }
}

Ref System (Entity Lifecycle)

package com.hypixel.hytale.component.system;

/**
 * System notified of entity lifecycle events.
 */
public abstract class RefSystem<ECS_TYPE> extends System<ECS_TYPE>
    implements QuerySystem<ECS_TYPE> {

    /**
     * Called when entity is added to store.
     * @param ref New entity reference
     * @param reason Why entity was added
     * @param store Parent store
     * @param buffer Command buffer
     */
    abstract void onEntityAdded(
        Ref<ECS_TYPE> ref,
        AddReason reason,
        Store<ECS_TYPE> store,
        CommandBuffer<ECS_TYPE> buffer);

    /**
     * Called when entity is being removed from store.
     * @param ref Entity being removed
     * @param reason Why entity is being removed
     * @param store Parent store
     * @param buffer Command buffer
     */
    abstract void onEntityRemove(
        Ref<ECS_TYPE> ref,
        RemoveReason reason,
        Store<ECS_TYPE> store,
        CommandBuffer<ECS_TYPE> buffer);
}

Store System

package com.hypixel.hytale.component.system;

/**
 * System notified of store lifecycle events.
 */
public abstract class StoreSystem<ECS_TYPE> extends System<ECS_TYPE> {
    /**
     * Called when system is added to store.
     * @param store Store this system was added to
     */
    abstract void onSystemAddedToStore(Store<ECS_TYPE> store);

    /**
     * Called when system is removed from store.
     * @param store Store this system was removed from
     */
    abstract void onSystemRemovedFromStore(Store<ECS_TYPE> store);
}

4.11 Query System

package com.hypixel.hytale.component.query;

import javax.annotation.Nonnull;

/**
 * Predicate for filtering entities by archetype.
 */
public interface Query<ECS_TYPE> {
    /**
     * Test if archetype matches this query.
     * @param archetype Archetype to test
     * @return true if matches
     */
    boolean test(Archetype<ECS_TYPE> archetype);

    /**
     * Check if query requires specific component.
     * @param type Component type to check
     * @return true if required
     */
    boolean requiresComponentType(ComponentType<ECS_TYPE, ?> type);

    /**
     * Validate query against registry.
     * @param registry Component registry
     */
    void validateRegistry(ComponentRegistry<ECS_TYPE> registry);

    /**
     * Validate query structure.
     */
    void validate();

    // ===== STATIC FACTORY METHODS =====

    /**
     * @return Query matching all archetypes
     */
    @Nonnull
    static <ECS_TYPE> AnyQuery<ECS_TYPE> any();

    /**
     * @return Query negating another query
     */
    @Nonnull
    static <ECS_TYPE> NotQuery<ECS_TYPE> not(Query<ECS_TYPE> query);

    /**
     * @return Query requiring all sub-queries to match
     */
    @Nonnull
    @SafeVarargs
    static <ECS_TYPE> AndQuery<ECS_TYPE> and(Query<ECS_TYPE>... queries);

    /**
     * @return Query requiring any sub-query to match
     */
    @Nonnull
    @SafeVarargs
    static <ECS_TYPE> OrQuery<ECS_TYPE> or(Query<ECS_TYPE>... queries);
}

Query Implementations

4.12 Command Buffer

Deferred command execution for safe entity modification during iteration.

package com.hypixel.hytale.component;

import java.util.Deque;
import java.util.function.Consumer;
import javax.annotation.Nonnull;

/**
 * Buffer for deferring entity operations.
 * Prevents concurrent modification during system iteration.
 */
public class CommandBuffer<ECS_TYPE> implements ComponentAccessor<ECS_TYPE> {
    private final Store<ECS_TYPE> store;
    private final Deque<Consumer<Store<ECS_TYPE>>> queue;
    private Ref<ECS_TYPE> trackedRef;
    private boolean trackedRefRemoved;
    private CommandBuffer<ECS_TYPE> parentBuffer;
    private Thread thread;

    /**
     * Queue operation for later execution.
     * @param consumer Operation to execute when buffer is flushed
     */
    void run(Consumer<Store<ECS_TYPE>> consumer);

    /**
     * Create nested command buffer.
     * @return Child command buffer
     */
    @Nonnull
    CommandBuffer<ECS_TYPE> fork();

    /**
     * Track if specific entity is removed.
     * @param ref Entity to track
     */
    void trackRef(Ref<ECS_TYPE> ref);

    /**
     * @return true if tracked entity was removed
     */
    boolean wasTrackedRefRemoved();

    // All ComponentAccessor methods are deferred to queue
    @Override
    public <T> T getComponent(Ref<ECS_TYPE> ref, ComponentType<ECS_TYPE, T> type) {
        // Deferred execution
    }
}

Usage Example

// During system tick, use command buffer for safe modifications
@Override
public void tick(float dt, int index, ArchetypeChunk<ChunkStore> chunk,
                Store<ChunkStore> store, CommandBuffer<ChunkStore> buffer) {

    Ref<ChunkStore> ref = chunk.refs[index];
    MyComponent comp = store.getComponent(ref, MY_COMPONENT_TYPE);

    if (shouldRemoveEntity(comp)) {
        // Don't modify directly - defer via buffer
        buffer.run(s -> s.removeEntity(ref, RemoveReason.LOGIC));
    }

    if (shouldAddComponent(comp)) {
        // Defer component addition
        buffer.addComponent(ref, OTHER_COMPONENT_TYPE, new OtherComponent());
    }
}

4.13 Dependency Management

package com.hypixel.hytale.component.dependency;

/**
 * Declares ordering between systems.
 */
public abstract class Dependency<ECS_TYPE> {
    protected final Order order;      // BEFORE or AFTER
    protected final int priority;     // Ordering within same relationship

    /**
     * Validate dependency against registry.
     */
    abstract void validate(ComponentRegistry<ECS_TYPE> registry);

    /**
     * Add edge to dependency graph.
     */
    abstract void resolveGraphEdge(
        ComponentRegistry<ECS_TYPE> registry,
        ISystem<ECS_TYPE> system,
        DependencyGraph<ECS_TYPE> graph);
}

/**
 * Dependency on another system type.
 */
public class SystemDependency<ECS_TYPE, T extends ISystem<ECS_TYPE>>
    extends Dependency<ECS_TYPE> {

    private final Class<T> systemClass;

    public SystemDependency(Order order, Class<T> systemClass);
    public SystemDependency(Order order, Class<T> systemClass, int priority);
    public SystemDependency(Order order, Class<T> systemClass, OrderPriority priority);
}

/**
 * Ordering enum.
 */
public enum Order {
    BEFORE,  // This system runs before dependency
    AFTER    // This system runs after dependency
}

Usage Example

public class MySystem extends EntityTickingSystem<ChunkStore> {
    @Override
    public Set<Dependency<ChunkStore>> getDependencies() {
        return Set.of(
            // Run after PhysicsSystem
            new SystemDependency<>(Order.AFTER, PhysicsSystem.class),
            // Run before RenderingSystem
            new SystemDependency<>(Order.BEFORE, RenderingSystem.class)
        );
    }
}

4.14 ECS Events

package com.hypixel.hytale.component.system;

/**
 * Base class for all ECS events.
 */
public abstract class EcsEvent {}

/**
 * Event targeted at specific entities.
 */
public class EntityEventType<ECS_TYPE, Event extends EcsEvent> {
    // Type handle for entity events
}

/**
 * Event broadcast to all listeners.
 */
public class WorldEventType<ECS_TYPE, Event extends EcsEvent> {
    // Type handle for world events
}

/**
 * Cancellable ECS event.
 */
public interface ICancellableEcsEvent {
    boolean isCancelled();
    void setCancelled(boolean cancelled);
}

Usage Example

// Define custom event
public class DamageEvent extends EcsEvent implements ICancellableEcsEvent {
    private final float damage;
    private final DamageCause cause;
    private boolean cancelled = false;

    public DamageEvent(float damage, DamageCause cause) {
        this.damage = damage;
        this.cause = cause;
    }

    public float getDamage() { return damage; }
    public DamageCause getCause() { return cause; }

    @Override
    public boolean isCancelled() { return cancelled; }
    @Override
    public void setCancelled(boolean cancelled) { this.cancelled = cancelled; }
}

// Register event type
EntityEventType<EntityStore, DamageEvent> DAMAGE_EVENT =
    registry.registerEntityEventType(DamageEvent.class);

// Invoke event
DamageEvent event = new DamageEvent(10.0f, DamageCause.FALL);
store.invoke(DAMAGE_EVENT, entityRef, event);

if (!event.isCancelled()) {
    // Apply damage
}

4.15 Spatial System

package com.hypixel.hytale.component.spatial;

/**
 * Resource containing spatial index for efficient proximity queries.
 */
public class SpatialResource<T, ECS_TYPE> implements Resource<ECS_TYPE> {
    private final SpatialData<Ref<ECS_TYPE>> spatialData;
    private final SpatialStructure<T> spatialStructure;

    public SpatialData<Ref<ECS_TYPE>> getSpatialData();
    public SpatialStructure<T> getSpatialStructure();

    @Override
    public Resource<ECS_TYPE> clone() { return this; }
}

/**
 * System that updates spatial index.
 */
public abstract class SpatialSystem<ECS_TYPE> extends TickingSystem<ECS_TYPE>
    implements QuerySystem<ECS_TYPE> {

    /**
     * Get position for entity in chunk.
     * @param chunk Archetype chunk
     * @param index Entity index
     * @return Entity position
     */
    abstract Vector3d getPosition(ArchetypeChunk<ECS_TYPE> chunk, int index);

    @Override
    void tick(float dt, int systemIndex, Store<ECS_TYPE> store) {
        // Rebuilds spatial structure each tick
    }
}

KD-Tree Implementation

package com.hypixel.hytale.component.spatial;

/**
 * KD-Tree for efficient spatial queries.
 */
public class KDTree<T> implements SpatialStructure<T> {
    // Binary space partition tree
    // Morton code-based traversal optimization
}

5. Registry System

Package: com.hypixel.hytale.registry Total Files: 3

The registry system provides type-safe registration and lookup for game objects.

5.1 Registry Interface

package com.hypixel.hytale.registry;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Type-safe registry for keyed objects.
 * @param <K> Key type
 * @param <V> Value type
 */
public interface Registry<K, V> {
    /**
     * Get value by key.
     * @param key Lookup key
     * @return Value if present
     */
    @Nullable
    V get(K key);

    /**
     * Get value as Optional.
     * @param key Lookup key
     * @return Optional containing value
     */
    @Nonnull
    Optional<V> getOptional(K key);

    /**
     * Check if key exists.
     * @param key Lookup key
     * @return true if registered
     */
    boolean containsKey(K key);

    /**
     * Get all registered keys.
     * @return Stream of keys
     */
    @Nonnull
    Stream<K> keys();

    /**
     * Get all registered values.
     * @return Stream of values
     */
    @Nonnull
    Stream<V> values();

    /**
     * Get count of registered entries.
     * @return Number of entries
     */
    int size();

    /**
     * Iterate over all entries.
     * @param consumer Entry consumer
     */
    void forEach(Consumer<V> consumer);
}

5.2 MutableRegistry

package com.hypixel.hytale.registry;

import javax.annotation.Nonnull;

/**
 * Registry that supports runtime registration.
 */
public interface MutableRegistry<K, V> extends Registry<K, V> {
    /**
     * Register value with key.
     * @param key Registration key
     * @param value Value to register
     * @return The registered value
     * @throws IllegalStateException if key already registered
     */
    @Nonnull
    V register(K key, V value);

    /**
     * Register value, replacing if exists.
     * @param key Registration key
     * @param value Value to register
     * @return Previous value if any
     */
    @Nullable
    V put(K key, V value);

    /**
     * Remove registration.
     * @param key Key to remove
     * @return Removed value if any
     */
    @Nullable
    V remove(K key);

    /**
     * Clear all registrations.
     */
    void clear();
}

5.3 RegistryKey

package com.hypixel.hytale.registry;

import javax.annotation.Nonnull;

/**
 * Typed registry key for compile-time safety.
 * @param <V> Value type this key is for
 */
public final class RegistryKey<V> {
    private final String namespace;
    private final String path;

    private RegistryKey(String namespace, String path) {
        this.namespace = namespace;
        this.path = path;
    }

    /**
     * Create key with namespace and path.
     * @param namespace Registry namespace (e.g., "hytale")
     * @param path Resource path (e.g., "blocks/stone")
     * @return Registry key
     */
    @Nonnull
    public static <V> RegistryKey<V> of(String namespace, String path) {
        return new RegistryKey<>(namespace, path);
    }

    /**
     * Create key from combined string.
     * @param combined "namespace:path" format
     * @return Registry key
     */
    @Nonnull
    public static <V> RegistryKey<V> parse(String combined) {
        int idx = combined.indexOf(':');
        if (idx < 0) {
            return new RegistryKey<>("hytale", combined);
        }
        return new RegistryKey<>(combined.substring(0, idx), combined.substring(idx + 1));
    }

    @Nonnull
    public String getNamespace() { return namespace; }

    @Nonnull
    public String getPath() { return path; }

    @Override
    public String toString() {
        return namespace + ":" + path;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof RegistryKey<?> that)) return false;
        return namespace.equals(that.namespace) && path.equals(that.path);
    }

    @Override
    public int hashCode() {
        return 31 * namespace.hashCode() + path.hashCode();
    }
}

6. Server Core APIs

Package: com.hypixel.hytale.server Total Files: 3,807

The server package contains the main game server implementation including universe management, entity handling, commands, and world logic.

6.1 Main Server Class

package com.hypixel.hytale.server;

import com.hypixel.hytale.event.IEventBus;
import javax.annotation.Nonnull;

/**
 * Main Hytale server class.
 */
public class HytaleServer {
    private static HytaleServer instance;

    /**
     * @return Singleton server instance
     */
    @Nonnull
    public static HytaleServer getInstance();

    /**
     * @return Server event bus
     */
    @Nonnull
    public IEventBus getEventBus();

    /**
     * @return Server tick rate (ticks per second)
     */
    public int getTickRate();

    /**
     * @return Current tick number
     */
    public long getCurrentTick();

    /**
     * Schedule task on main thread.
     * @param runnable Task to run
     */
    public void runOnMainThread(Runnable runnable);

    /**
     * Check if current thread is main thread.
     * @return true if on main thread
     */
    public boolean isMainThread();
}

6.2 Universe (World Container)

package com.hypixel.hytale.server.core.universe;

import com.hypixel.hytale.server.core.player.Player;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Top-level world container managing all dimensions, players, and game state.
 */
public class Universe {
    // ===== PLAYER MANAGEMENT =====

    /**
     * Get all connected players.
     * @return Collection of players
     */
    @Nonnull
    public Collection<Player> getPlayers();

    /**
     * Get player by UUID.
     * @param uuid Player UUID
     * @return Player or null
     */
    @Nullable
    public Player getPlayer(UUID uuid);

    /**
     * Get player by name.
     * @param name Player name
     * @return Player or null
     */
    @Nullable
    public Player getPlayerByName(String name);

    /**
     * Get player count.
     * @return Number of connected players
     */
    public int getPlayerCount();

    // ===== WORLD MANAGEMENT =====

    /**
     * Get all loaded worlds.
     * @return Collection of worlds
     */
    @Nonnull
    public Collection<World> getWorlds();

    /**
     * Get world by name.
     * @param name World name
     * @return World or null
     */
    @Nullable
    public World getWorld(String name);

    /**
     * Get default/main world.
     * @return Default world
     */
    @Nonnull
    public World getDefaultWorld();

    /**
     * Load world from storage.
     * @param name World name
     * @return Future completing with loaded world
     */
    @Nonnull
    public CompletableFuture<World> loadWorld(String name);

    /**
     * Unload world.
     * @param world World to unload
     * @return Future completing when unloaded
     */
    @Nonnull
    public CompletableFuture<Void> unloadWorld(World world);

    // ===== TIME =====

    /**
     * @return Server uptime in milliseconds
     */
    public long getUptime();

    /**
     * @return Current tick
     */
    public long getCurrentTick();
}

6.3 World

package com.hypixel.hytale.server.core.world;

import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.math.Vector3d;
import com.hypixel.hytale.math.Vector3i;
import java.util.Collection;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Represents a single dimension/world with chunks, entities, and game rules.
 */
public class World {
    // ===== PROPERTIES =====

    /**
     * @return World name
     */
    @Nonnull
    public String getName();

    /**
     * @return World UUID
     */
    @Nonnull
    public UUID getUUID();

    /**
     * @return World seed
     */
    public long getSeed();

    // ===== CHUNK ACCESS =====

    /**
     * Get chunk at position.
     * @param x Chunk X coordinate
     * @param z Chunk Z coordinate
     * @return Chunk or null if not loaded
     */
    @Nullable
    public Chunk getChunk(int x, int z);

    /**
     * Get chunk at block position.
     * @param position Block position
     * @return Chunk containing position
     */
    @Nullable
    public Chunk getChunkAt(Vector3i position);

    /**
     * Load chunk at position.
     * @param x Chunk X coordinate
     * @param z Chunk Z coordinate
     * @return Loaded chunk
     */
    @Nonnull
    public Chunk loadChunk(int x, int z);

    /**
     * Check if chunk is loaded.
     * @param x Chunk X coordinate
     * @param z Chunk Z coordinate
     * @return true if loaded
     */
    public boolean isChunkLoaded(int x, int z);

    /**
     * Get all loaded chunks.
     * @return Collection of chunks
     */
    @Nonnull
    public Collection<Chunk> getLoadedChunks();

    // ===== BLOCK ACCESS =====

    /**
     * Get block at position.
     * @param position Block position
     * @return Block state
     */
    @Nonnull
    public BlockState getBlock(Vector3i position);

    /**
     * Set block at position.
     * @param position Block position
     * @param state New block state
     */
    public void setBlock(Vector3i position, BlockState state);

    /**
     * Set block with update flags.
     * @param position Block position
     * @param state New block state
     * @param flags Update flags (e.g., NOTIFY_NEIGHBORS)
     */
    public void setBlock(Vector3i position, BlockState state, int flags);

    // ===== ENTITY ACCESS =====

    /**
     * @return Entity store for this world
     */
    @Nonnull
    public Store<?> getEntityStore();

    /**
     * Get entities in radius.
     * @param center Center position
     * @param radius Search radius
     * @return Entities within radius
     */
    @Nonnull
    public Collection<?> getEntitiesInRadius(Vector3d center, double radius);

    /**
     * Get entities in bounding box.
     * @param min Minimum corner
     * @param max Maximum corner
     * @return Entities within box
     */
    @Nonnull
    public Collection<?> getEntitiesInBox(Vector3d min, Vector3d max);

    // ===== TIME =====

    /**
     * @return World time (0-24000)
     */
    public long getTime();

    /**
     * Set world time.
     * @param time New time (0-24000)
     */
    public void setTime(long time);

    /**
     * @return Day count
     */
    public long getDay();

    // ===== WEATHER =====

    /**
     * @return true if raining
     */
    public boolean isRaining();

    /**
     * Set rain state.
     * @param raining Whether to rain
     */
    public void setRaining(boolean raining);

    /**
     * @return true if thundering
     */
    public boolean isThundering();

    /**
     * Set thunder state.
     * @param thundering Whether to thunder
     */
    public void setThundering(boolean thundering);
}

6.4 Chunk

package com.hypixel.hytale.server.core.world;

import com.hypixel.hytale.math.Vector3i;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * 16x384x16 block section of the world.
 */
public class Chunk {
    public static final int WIDTH = 16;
    public static final int HEIGHT = 384;  // -64 to +320
    public static final int DEPTH = 16;

    /**
     * @return Chunk X coordinate
     */
    public int getX();

    /**
     * @return Chunk Z coordinate
     */
    public int getZ();

    /**
     * @return Containing world
     */
    @Nonnull
    public World getWorld();

    /**
     * Get block at local coordinates.
     * @param x Local X (0-15)
     * @param y World Y (-64 to 319)
     * @param z Local Z (0-15)
     * @return Block state
     */
    @Nonnull
    public BlockState getBlock(int x, int y, int z);

    /**
     * Set block at local coordinates.
     * @param x Local X (0-15)
     * @param y World Y (-64 to 319)
     * @param z Local Z (0-15)
     * @param state New block state
     */
    public void setBlock(int x, int y, int z, BlockState state);

    /**
     * Get section at Y level.
     * @param sectionY Section index (0-23)
     * @return Chunk section
     */
    @Nullable
    public ChunkSection getSection(int sectionY);

    /**
     * @return true if chunk has been modified since last save
     */
    public boolean isDirty();

    /**
     * Mark chunk as modified.
     */
    public void setDirty();

    /**
     * Get block world position.
     * @param localX Local X (0-15)
     * @param y World Y
     * @param localZ Local Z (0-15)
     * @return World position
     */
    @Nonnull
    public Vector3i getBlockPosition(int localX, int y, int localZ);
}

6.5 Player

package com.hypixel.hytale.server.core.player;

import com.hypixel.hytale.math.Vector3d;
import com.hypixel.hytale.protocol.packet.IPacket;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Connected player with network connection and game state.
 */
public class Player {
    // ===== IDENTITY =====

    /**
     * @return Player UUID
     */
    @Nonnull
    public UUID getUUID();

    /**
     * @return Player username
     */
    @Nonnull
    public String getName();

    /**
     * @return Display name (may include formatting)
     */
    @Nonnull
    public String getDisplayName();

    // ===== POSITION =====

    /**
     * @return Current position
     */
    @Nonnull
    public Vector3d getPosition();

    /**
     * Set position.
     * @param position New position
     */
    public void setPosition(Vector3d position);

    /**
     * Teleport player.
     * @param position Destination
     */
    public void teleport(Vector3d position);

    /**
     * Teleport to world and position.
     * @param world Target world
     * @param position Destination
     * @return Future completing when teleported
     */
    @Nonnull
    public CompletableFuture<Void> teleport(World world, Vector3d position);

    /**
     * @return Yaw rotation (horizontal)
     */
    public float getYaw();

    /**
     * @return Pitch rotation (vertical)
     */
    public float getPitch();

    // ===== WORLD =====

    /**
     * @return Current world
     */
    @Nonnull
    public World getWorld();

    /**
     * @return Current chunk
     */
    @Nullable
    public Chunk getChunk();

    // ===== GAME MODE =====

    /**
     * @return Current game mode
     */
    @Nonnull
    public GameMode getGameMode();

    /**
     * Set game mode.
     * @param mode New game mode
     */
    public void setGameMode(GameMode mode);

    // ===== HEALTH =====

    /**
     * @return Current health
     */
    public float getHealth();

    /**
     * Set health.
     * @param health New health value
     */
    public void setHealth(float health);

    /**
     * @return Maximum health
     */
    public float getMaxHealth();

    /**
     * @return true if player is dead
     */
    public boolean isDead();

    // ===== NETWORK =====

    /**
     * Send packet to player.
     * @param packet Packet to send
     */
    public void sendPacket(IPacket packet);

    /**
     * @return Ping in milliseconds
     */
    public int getPing();

    /**
     * Disconnect player.
     * @param reason Disconnect reason
     */
    public void disconnect(String reason);

    // ===== PERMISSIONS =====

    /**
     * Check permission.
     * @param permission Permission node
     * @return true if has permission
     */
    public boolean hasPermission(String permission);

    /**
     * @return true if player is operator
     */
    public boolean isOp();

    // ===== MESSAGING =====

    /**
     * Send message to player.
     * @param message Message text
     */
    public void sendMessage(String message);

    /**
     * Send action bar message.
     * @param message Action bar text
     */
    public void sendActionBar(String message);

    /**
     * Send title.
     * @param title Title text
     * @param subtitle Subtitle text
     * @param fadeIn Fade in ticks
     * @param stay Stay ticks
     * @param fadeOut Fade out ticks
     */
    public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut);
}

/**
 * Game modes.
 */
public enum GameMode {
    SURVIVAL,
    CREATIVE,
    ADVENTURE,
    SPECTATOR
}

6.6 Command System

package com.hypixel.hytale.server.core.command;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;

/**
 * Command registration and execution manager.
 */
public class CommandManager {
    /**
     * Register command.
     * @param command Command to register
     */
    public void registerCommand(ICommand command);

    /**
     * Unregister command.
     * @param name Command name
     * @return true if removed
     */
    public boolean unregisterCommand(String name);

    /**
     * Get registered command.
     * @param name Command name
     * @return Command or null
     */
    @Nullable
    public ICommand getCommand(String name);

    /**
     * Get all registered commands.
     * @return Collection of commands
     */
    @Nonnull
    public Collection<ICommand> getCommands();

    /**
     * Execute command.
     * @param sender Command sender
     * @param commandLine Full command line
     * @return Future completing with result
     */
    @Nonnull
    public CompletableFuture<CommandResult> executeCommand(
        ICommandSender sender, String commandLine);

    /**
     * Get tab completions.
     * @param sender Command sender
     * @param commandLine Partial command line
     * @return List of completions
     */
    @Nonnull
    public Collection<String> getCompletions(ICommandSender sender, String commandLine);
}

/**
 * Command interface.
 */
public interface ICommand {
    /**
     * @return Command name (primary)
     */
    @Nonnull
    String getName();

    /**
     * @return Command aliases
     */
    @Nonnull
    default Collection<String> getAliases() {
        return Collection.of();
    }

    /**
     * @return Command description
     */
    @Nonnull
    String getDescription();

    /**
     * @return Usage string
     */
    @Nonnull
    String getUsage();

    /**
     * @return Required permission or null
     */
    @Nullable
    default String getPermission() {
        return null;
    }

    /**
     * Execute command.
     * @param sender Command sender
     * @param args Command arguments
     * @return Execution result
     */
    @Nonnull
    CommandResult execute(ICommandSender sender, String[] args);

    /**
     * Get tab completions.
     * @param sender Command sender
     * @param args Current arguments
     * @return Completions for next argument
     */
    @Nonnull
    default Collection<String> tabComplete(ICommandSender sender, String[] args) {
        return Collection.of();
    }
}

/**
 * Entity that can send commands.
 */
public interface ICommandSender {
    /**
     * @return Sender name
     */
    @Nonnull
    String getName();

    /**
     * Send message to sender.
     * @param message Message text
     */
    void sendMessage(String message);

    /**
     * Check permission.
     * @param permission Permission node
     * @return true if permitted
     */
    boolean hasPermission(String permission);
}

/**
 * Command execution result.
 */
public enum CommandResult {
    SUCCESS,
    FAILURE,
    INVALID_SYNTAX,
    NO_PERMISSION,
    PLAYER_ONLY,
    CONSOLE_ONLY
}

7. Protocol & Networking

Package: com.hypixel.hytale.protocol Total Files: 737 Total Packets: 268

The protocol system handles all network communication between server and clients using a binary protocol over QUIC.

7.1 Protocol Constants

package com.hypixel.hytale.protocol;

public final class ProtocolConstants {
    /**
     * Protocol version number.
     */
    public static final int PROTOCOL_VERSION = 1;

    /**
     * Protocol hash for version verification.
     */
    public static final String PROTOCOL_HASH =
        "6708f121966c1c443f4b0eb525b2f81d0a8dc61f5003a692a8fa157e5e02cea9";

    /**
     * Maximum packet size (before compression).
     */
    public static final int MAX_PACKET_SIZE = 2097152;  // 2 MB

    /**
     * Compression threshold in bytes.
     */
    public static final int COMPRESSION_THRESHOLD = 256;
}

7.2 Packet Interface

package com.hypixel.hytale.protocol.packet;

import com.hypixel.hytale.codec.BinaryReader;
import com.hypixel.hytale.codec.BinaryWriter;
import javax.annotation.Nonnull;

/**
 * Base interface for all network packets.
 */
public interface IPacket {
    /**
     * @return Unique packet ID
     */
    int getId();

    /**
     * Write packet data to binary stream.
     * @param writer Binary output
     */
    void write(@Nonnull BinaryWriter writer);

    /**
     * Read packet data from binary stream.
     * @param reader Binary input
     */
    void read(@Nonnull BinaryReader reader);

    /**
     * @return Packet direction (CLIENT_TO_SERVER, SERVER_TO_CLIENT, BOTH)
     */
    @Nonnull
    PacketDirection getDirection();

    /**
     * @return Connection state when this packet is valid
     */
    @Nonnull
    ConnectionState getState();
}

/**
 * Packet flow direction.
 */
public enum PacketDirection {
    CLIENT_TO_SERVER,
    SERVER_TO_CLIENT,
    BOTH
}

/**
 * Connection state machine.
 */
public enum ConnectionState {
    HANDSHAKE,
    STATUS,
    LOGIN,
    PLAY
}

7.3 Packet Registry

package com.hypixel.hytale.protocol.packet;

import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Registry for packet types with ID-based lookup.
 */
public class PacketRegistry {
    /**
     * Register packet type.
     * @param id Packet ID
     * @param clazz Packet class
     * @param supplier Factory
     * @param direction Packet direction
     * @param state Required connection state
     */
    public void registerPacket(
        int id,
        Class<? extends IPacket> clazz,
        Supplier<? extends IPacket> supplier,
        PacketDirection direction,
        ConnectionState state);

    /**
     * Create packet instance by ID.
     * @param id Packet ID
     * @return New packet instance
     */
    @Nullable
    public IPacket createPacket(int id);

    /**
     * Get packet class by ID.
     * @param id Packet ID
     * @return Packet class
     */
    @Nullable
    public Class<? extends IPacket> getPacketClass(int id);

    /**
     * Get packet ID by class.
     * @param clazz Packet class
     * @return Packet ID or -1
     */
    public int getPacketId(Class<? extends IPacket> clazz);
}

7.4 Complete Packet List (268 Packets)

Connection Packets (0-9)

ID Packet Direction Description
0 HandshakePacket C→S Initial connection handshake
1 DisconnectPacket S→C Server disconnect with reason
2 PingPacket Both Latency measurement request
3 PongPacket Both Latency measurement response
4 KeepAlivePacket Both Connection keep-alive
5 CompressionPacket S→C Enable compression
6 EncryptionRequestPacket S→C Request encryption setup
7 EncryptionResponsePacket C→S Encryption key exchange
8 LoginSuccessPacket S→C Login completed
9 SetProtocolPacket Both Protocol version negotiation

Authentication Packets (10-19)

ID Packet Direction Description
10 AuthRequestPacket C→S Authentication request
11 AuthResponsePacket S→C Authentication result
12 AuthChallengePacket S→C Additional auth challenge
13 AuthProofPacket C→S Challenge response
14 ServerPasswordRequestPacket S→C Request server password
15 ServerPasswordPacket C→S Server password submission
16 TokenRefreshPacket Both Session token refresh
17 SessionDataPacket S→C Session information

World Initialization (20-39)

ID Packet Direction Description
20 WorldInfoPacket S→C World metadata
21 SpawnPositionPacket S→C Player spawn point
22 WorldSettingsPacket S→C Game rules and settings
23 DifficultyPacket S→C Difficulty setting
24 GameModePacket S→C Player game mode
25 AbilitiesPacket S→C Player abilities
26 InitialInventoryPacket S→C Starting inventory
27 RecipeBookPacket S→C Known recipes
28 AdvancementsPacket S→C Achievement progress
29 StatisticsPacket S→C Player statistics
30 TagsPacket S→C Data-driven tags
31 RegistrySyncPacket S→C Registry data sync
32 DimensionTypePacket S→C Dimension properties
33 BiomeRegistryPacket S→C Biome definitions
34 WorldBorderPacket S→C World border settings
35 TimeUpdatePacket S→C World time sync
36 WeatherPacket S→C Weather state
37 RespawnPacket S→C Player respawn data
38 FeatureFlagsPacket S→C Enabled features
39 ConfigurationEndPacket S→C Configuration complete

Asset Configuration (40-99)

ID Packet Direction Description
40 AssetPackInfoPacket S→C Asset pack metadata
41 AssetPackRequestPacket C→S Request asset pack
42 AssetPackDataPacket S→C Asset pack chunk
43 AssetPackStatusPacket C→S Asset download status
44 AssetPackRemovePacket S→C Remove asset pack
45 BlockRegistryPacket S→C Block type registry
46 ItemRegistryPacket S→C Item type registry
47 EntityRegistryPacket S→C Entity type registry
48 ParticleRegistryPacket S→C Particle definitions
49 SoundRegistryPacket S→C Sound definitions
50-59 CustomAsset*Packet Both Custom asset types
60-69 Model*Packet S→C 3D model data
70-79 Texture*Packet S→C Texture data
80-89 Animation*Packet S→C Animation data
90-99 Shader*Packet S→C Shader programs

Player Movement (100-119)

ID Packet Direction Description
100 PlayerPositionPacket C→S Position update
101 PlayerPositionRotationPacket C→S Position + rotation
102 PlayerRotationPacket C→S Rotation only
103 PlayerOnGroundPacket C→S Ground state
104 PlayerMovePacket S→C Confirm movement
105 TeleportPacket S→C Force teleport
106 TeleportConfirmPacket C→S Teleport acknowledged
107 VehicleMovePacket Both Vehicle movement
108 SteerVehiclePacket C→S Vehicle input
109 PlayerInputPacket C→S Input state
110 FlyingPacket C→S Flying state
111 SprintingPacket C→S Sprint state
112 SneakingPacket C→S Sneak state
113 SwimmingPacket C→S Swim state
114 ClimbingPacket C→S Climb state
115 JumpPacket C→S Jump action
116 VelocityPacket S→C Velocity update
117 PushPacket S→C Push force

Player Interaction (120-130)

ID Packet Direction Description
120 InteractPacket C→S Entity interaction
121 AttackPacket C→S Attack action
122 UseItemPacket C→S Use held item
123 UseBlockPacket C→S Use block
124 DropItemPacket C→S Drop item
125 SwapHandsPacket C→S Swap main/offhand
126 HotbarSelectPacket C→S Hotbar slot change
127 PickBlockPacket C→S Pick block (creative)
128 PlayerActionPacket C→S Various actions
129 PlayerAbilitiesPacket C→S Ability usage
130 RespawnRequestPacket C→S Request respawn

World State (131-159)

ID Packet Direction Description
131 ChunkDataPacket S→C Full chunk data
132 ChunkDeltaPacket S→C Chunk modifications
133 ChunkUnloadPacket S→C Unload chunk
134 LightUpdatePacket S→C Light data
135 BlockUpdatePacket S→C Single block change
136 MultiBlockUpdatePacket S→C Multiple blocks
137 BlockEntityDataPacket S→C Block entity NBT
138 BlockActionPacket S→C Block animations
139 BlockBreakAnimationPacket S→C Break progress
140 BlockBreakPacket C→S Break block
141 BlockPlacePacket C→S Place block
142 SignEditPacket C→S Edit sign text
143 SignUpdatePacket S→C Sign content
144 ExplosionPacket S→C Explosion effect
145 ParticlePacket S→C Spawn particles
146 SoundPacket S→C Play sound
147 StopSoundPacket S→C Stop sound
148 LevelEventPacket S→C World events
149 GameEventPacket S→C Game state events
150 SetTickingStatePacket S→C Ticking control
151 SetCenterChunkPacket S→C View center
152 SetChunkRadiusPacket S→C View distance
153 SetSimulationDistancePacket S→C Simulation distance

Entity Updates (160-179)

ID Packet Direction Description
160 SpawnEntityPacket S→C Spawn entity
161 SpawnLivingEntityPacket S→C Spawn living entity
162 SpawnPlayerPacket S→C Spawn player entity
163 SpawnPaintingPacket S→C Spawn painting
164 SpawnXPOrbPacket S→C Spawn XP orb
165 RemoveEntitiesPacket S→C Despawn entities
166 EntityMovePacket S→C Entity movement
167 EntityMoveRotationPacket S→C Movement + rotation
168 EntityRotationPacket S→C Rotation only
169 EntityHeadRotationPacket S→C Head rotation
170 EntityTeleportPacket S→C Entity teleport
171 EntityVelocityPacket S→C Entity velocity
172 EntityStatusPacket S→C Entity status flags
173 EntityEventPacket S→C Entity events
174 EntityMetadataPacket S→C Entity metadata
175 EntityEquipmentPacket S→C Equipment slots
176 EntityAttributesPacket S→C Entity attributes
177 EntityEffectPacket S→C Status effects
178 RemoveEntityEffectPacket S→C Remove effect
179 EntityAnimationPacket S→C Play animation

Inventory (180-199)

ID Packet Direction Description
180 InventoryContentPacket S→C Full inventory
181 InventorySlotPacket S→C Single slot update
182 SetCarriedItemPacket S→C Held item slot
183 ContainerOpenPacket S→C Open container GUI
184 ContainerClosePacket Both Close container
185 ContainerClickPacket C→S Inventory click
186 ContainerConfirmPacket Both Transaction confirm
187 CreativeInventoryPacket C→S Creative mode set
188 QuickMovePacket C→S Shift-click move
189 CraftPacket C→S Crafting action
190 CraftResultPacket S→C Crafting result
191 RecipeUpdatePacket S→C Recipe changes
192 MerchantOffersPacket S→C Villager trades
193 SelectTradePacket C→S Select trade
194 EnchantPacket C→S Enchant item
195 AnvilPacket C→S Anvil operation
196 BeaconPacket C→S Beacon effect
197 LoomPacket C→S Banner pattern

UI/Windows (200-234)

ID Packet Direction Description
200 ChatPacket Both Chat message
201 SystemChatPacket S→C System message
202 ActionBarPacket S→C Action bar text
203 TitlePacket S→C Title display
204 SubtitlePacket S→C Subtitle display
205 TitleTimesPacket S→C Title timing
206 ClearTitlePacket S→C Clear title
207 BossBarPacket S→C Boss bar update
208 TabListPacket S→C Player list
209 TabListHeaderFooterPacket S→C Tab header/footer
210 ScoreboardObjectivePacket S→C Scoreboard objective
211 ScoreboardScorePacket S→C Score update
212 ScoreboardTeamPacket S→C Team update
213 ScoreboardDisplayPacket S→C Display slot
214 CommandSuggestionsPacket S→C Command completions
215 CommandSuggestRequestPacket C→S Request completions
216 DeclareCommandsPacket S→C Command tree
217 ToastPacket S→C Toast notification
218 OverlayMessagePacket S→C Screen overlay
219 CooldownPacket S→C Item cooldown
220 SetExperiencePacket S→C XP bar update
221 SetHealthPacket S→C Health update
222 HungerPacket S→C Hunger update
223 DeathScreenPacket S→C Death screen
224 BookOpenPacket S→C Open book GUI
225 BookEditPacket C→S Edit book
226 BookSignPacket C→S Sign book
227 SelectAdvancementTabPacket Both Advancement tab
228 AdvancementProgressPacket S→C Advancement earned
229 RecipeToastPacket S→C Recipe unlocked
230 HorseScreenOpenPacket S→C Horse inventory
231 MapDataPacket S→C Map item data
232 DebugScreenPacket S→C F3 debug data
233 ResourcePackPacket S→C Resource pack
234 ResourcePackStatusPacket C→S Pack status

World Map (240-245)

ID Packet Direction Description
240 WorldMapDataPacket S→C Full map data
241 WorldMapUpdatePacket S→C Map delta
242 WorldMapPingPacket Both Map ping
243 WorldMapMarkerPacket S→C Map markers
244 WorldMapChunkPacket S→C Map chunk
245 WorldMapCenterPacket S→C Map center

Camera & View (280-294)

ID Packet Direction Description
280 CameraPacket S→C Set camera entity
281 CameraModePacket S→C Camera mode
282 CameraShakePacket S→C Screen shake
283 CameraFadePacket S→C Screen fade
284 CameraTintPacket S→C Screen tint
285 SetViewDistancePacket S→C Render distance
286 SetFOVPacket S→C Field of view
287 LookAtPacket S→C Force look direction
288 RaycastPacket C→S Client raycast
289 RaycastResultPacket S→C Raycast result
290 InteractionModePacket S→C Interaction state
291 CursorPacket C→S Cursor position
292 SelectTargetPacket Both Target selection
293 HighlightEntityPacket S→C Entity highlight
294 HighlightBlockPacket S→C Block highlight

Asset Editor (300-361)

ID Packet Direction Description
300 EditorModePacket Both Enter/exit editor
301-310 EditorBlock*Packet Both Block editing
311-320 EditorEntity*Packet Both Entity editing
321-330 EditorTerrain*Packet Both Terrain tools
331-340 EditorPrefab*Packet Both Prefab operations
341-350 EditorUndo*Packet Both Undo/redo
351-361 EditorMisc*Packet Both Misc editor ops

Builder Tools (400-423)

ID Packet Direction Description
400 BuilderModePacket Both Builder mode toggle
401 BuilderSelectionPacket C→S Selection bounds
402 BuilderCopyPacket C→S Copy selection
403 BuilderCutPacket C→S Cut selection
404 BuilderPastePacket C→S Paste clipboard
405 BuilderFillPacket C→S Fill selection
406 BuilderReplacePacket C→S Replace blocks
407 BuilderDeletePacket C→S Delete selection
408 BuilderRotatePacket C→S Rotate selection
409 BuilderFlipPacket C→S Mirror selection
410 BuilderMovePacket C→S Move selection
411 BuilderUndoPacket C→S Undo operation
412 BuilderRedoPacket C→S Redo operation
413 BuilderBrushPacket C→S Brush settings
414 BuilderPaintPacket C→S Paint operation
415 BuilderSmoothPacket C→S Smooth terrain
416 BuilderNoisePacket C→S Apply noise
417 SchematicLoadPacket C→S Load schematic
418 SchematicSavePacket C→S Save schematic
419 SchematicListPacket S→C Available schematics
420 SchematicDataPacket Both Schematic data
421 BlueprintPacket Both Blueprint data
422 PrefabSpawnPacket C→S Spawn prefab
423 PrefabListPacket S→C Available prefabs

7.5 Binary Serialization

package com.hypixel.hytale.codec;

import java.nio.ByteBuffer;
import javax.annotation.Nonnull;

/**
 * Binary stream writer for packet serialization.
 */
public class BinaryWriter {
    private ByteBuffer buffer;

    public void writeByte(byte value);
    public void writeShort(short value);
    public void writeInt(int value);
    public void writeLong(long value);
    public void writeFloat(float value);
    public void writeDouble(double value);
    public void writeBoolean(boolean value);

    /**
     * Write variable-length integer (1-5 bytes).
     */
    public void writeVarInt(int value);

    /**
     * Write variable-length long (1-10 bytes).
     */
    public void writeVarLong(long value);

    /**
     * Write UTF-8 string with length prefix.
     */
    public void writeString(@Nonnull String value);

    /**
     * Write UUID as two longs.
     */
    public void writeUUID(@Nonnull UUID value);

    /**
     * Write byte array with length prefix.
     */
    public void writeByteArray(@Nonnull byte[] value);

    /**
     * Write vector3d as 3 doubles.
     */
    public void writeVector3d(@Nonnull Vector3d value);

    /**
     * Write vector3i as 3 ints.
     */
    public void writeVector3i(@Nonnull Vector3i value);

    /**
     * Write NBT compound.
     */
    public void writeNBT(@Nonnull NBTCompound value);
}

/**
 * Binary stream reader for packet deserialization.
 */
public class BinaryReader {
    private ByteBuffer buffer;

    public byte readByte();
    public short readShort();
    public int readInt();
    public long readLong();
    public float readFloat();
    public double readDouble();
    public boolean readBoolean();

    public int readVarInt();
    public long readVarLong();

    @Nonnull
    public String readString();

    @Nonnull
    public String readString(int maxLength);

    @Nonnull
    public UUID readUUID();

    @Nonnull
    public byte[] readByteArray();

    @Nonnull
    public byte[] readByteArray(int maxLength);

    @Nonnull
    public Vector3d readVector3d();

    @Nonnull
    public Vector3i readVector3i();

    @Nonnull
    public NBTCompound readNBT();

    /**
     * @return Remaining bytes in buffer
     */
    public int remaining();

    /**
     * Skip bytes.
     * @param count Bytes to skip
     */
    public void skip(int count);
}

7.6 Compression

The protocol uses Zstandard (Zstd) compression for packets above the threshold.

package com.hypixel.hytale.protocol.compression;

/**
 * Zstd compression utilities.
 */
public class ZstdCompression {
    /**
     * Default compression level (3).
     */
    public static final int DEFAULT_LEVEL = 3;

    /**
     * Compress data.
     * @param data Input data
     * @return Compressed data
     */
    @Nonnull
    public static byte[] compress(@Nonnull byte[] data);

    /**
     * Compress with level.
     * @param data Input data
     * @param level Compression level (1-22)
     * @return Compressed data
     */
    @Nonnull
    public static byte[] compress(@Nonnull byte[] data, int level);

    /**
     * Decompress data.
     * @param data Compressed data
     * @param maxSize Maximum output size
     * @return Decompressed data
     */
    @Nonnull
    public static byte[] decompress(@Nonnull byte[] data, int maxSize);
}

8. Storage & Persistence

Package: com.hypixel.hytale.storage Total Files: ~20

The storage system handles world persistence, player data, and configuration storage.

8.1 Storage Interface

package com.hypixel.hytale.storage;

import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Generic key-value storage interface.
 */
public interface IStorage<K, V> {
    /**
     * Get value by key.
     * @param key Lookup key
     * @return Future with value or null
     */
    @Nonnull
    CompletableFuture<V> get(@Nonnull K key);

    /**
     * Store value.
     * @param key Storage key
     * @param value Value to store
     * @return Future completing when stored
     */
    @Nonnull
    CompletableFuture<Void> put(@Nonnull K key, @Nonnull V value);

    /**
     * Delete value.
     * @param key Key to delete
     * @return Future with deleted value or null
     */
    @Nonnull
    CompletableFuture<V> delete(@Nonnull K key);

    /**
     * Check if key exists.
     * @param key Lookup key
     * @return Future with existence
     */
    @Nonnull
    CompletableFuture<Boolean> exists(@Nonnull K key);
}

8.2 Chunk Storage

package com.hypixel.hytale.storage.chunk;

import com.hypixel.hytale.server.core.world.Chunk;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;

/**
 * Chunk data persistence.
 */
public interface IChunkStorage {
    /**
     * Load chunk from storage.
     * @param worldId World UUID
     * @param x Chunk X
     * @param z Chunk Z
     * @return Future with chunk data or null
     */
    @Nonnull
    CompletableFuture<ChunkData> loadChunk(
        @Nonnull UUID worldId, int x, int z);

    /**
     * Save chunk to storage.
     * @param worldId World UUID
     * @param chunk Chunk to save
     * @return Future completing when saved
     */
    @Nonnull
    CompletableFuture<Void> saveChunk(
        @Nonnull UUID worldId, @Nonnull Chunk chunk);

    /**
     * Delete chunk from storage.
     * @param worldId World UUID
     * @param x Chunk X
     * @param z Chunk Z
     * @return Future completing when deleted
     */
    @Nonnull
    CompletableFuture<Void> deleteChunk(
        @Nonnull UUID worldId, int x, int z);

    /**
     * Check if chunk exists in storage.
     * @param worldId World UUID
     * @param x Chunk X
     * @param z Chunk Z
     * @return Future with existence
     */
    @Nonnull
    CompletableFuture<Boolean> chunkExists(
        @Nonnull UUID worldId, int x, int z);
}

/**
 * Serialized chunk data.
 */
public class ChunkData {
    private final int x;
    private final int z;
    private final byte[] blockData;
    private final byte[] lightData;
    private final NBTCompound blockEntities;
    private final NBTCompound entities;
    private final long lastModified;

    // Getters...
}

8.3 Player Storage

package com.hypixel.hytale.storage.player;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;

/**
 * Player data persistence.
 */
public interface IPlayerStorage {
    /**
     * Load player data.
     * @param uuid Player UUID
     * @return Future with player data
     */
    @Nonnull
    CompletableFuture<PlayerData> loadPlayer(@Nonnull UUID uuid);

    /**
     * Save player data.
     * @param uuid Player UUID
     * @param data Player data
     * @return Future completing when saved
     */
    @Nonnull
    CompletableFuture<Void> savePlayer(
        @Nonnull UUID uuid, @Nonnull PlayerData data);

    /**
     * Check if player data exists.
     * @param uuid Player UUID
     * @return Future with existence
     */
    @Nonnull
    CompletableFuture<Boolean> playerExists(@Nonnull UUID uuid);
}

/**
 * Serialized player data.
 */
public class PlayerData {
    private Vector3d position;
    private float yaw;
    private float pitch;
    private String worldId;
    private GameMode gameMode;
    private float health;
    private float maxHealth;
    private int foodLevel;
    private float saturation;
    private int experienceLevel;
    private float experienceProgress;
    private NBTCompound inventory;
    private NBTCompound enderChest;
    private NBTCompound abilities;
    private NBTCompound attributes;
    private NBTCompound effects;
    private NBTCompound advancements;
    private NBTCompound statistics;
    private NBTCompound recipes;

    // Getters and setters...
}

8.4 NBT (Named Binary Tag)

package com.hypixel.hytale.storage.nbt;

import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * NBT compound tag for structured data.
 */
public class NBTCompound implements NBTTag {
    private final Map<String, NBTTag> tags;

    public NBTCompound();

    // ===== TYPE-SPECIFIC GETTERS =====

    public byte getByte(@Nonnull String key);
    public byte getByte(@Nonnull String key, byte defaultValue);

    public short getShort(@Nonnull String key);
    public short getShort(@Nonnull String key, short defaultValue);

    public int getInt(@Nonnull String key);
    public int getInt(@Nonnull String key, int defaultValue);

    public long getLong(@Nonnull String key);
    public long getLong(@Nonnull String key, long defaultValue);

    public float getFloat(@Nonnull String key);
    public float getFloat(@Nonnull String key, float defaultValue);

    public double getDouble(@Nonnull String key);
    public double getDouble(@Nonnull String key, double defaultValue);

    @Nonnull
    public String getString(@Nonnull String key);
    @Nonnull
    public String getString(@Nonnull String key, @Nonnull String defaultValue);

    @Nonnull
    public byte[] getByteArray(@Nonnull String key);

    @Nonnull
    public int[] getIntArray(@Nonnull String key);

    @Nonnull
    public long[] getLongArray(@Nonnull String key);

    @Nullable
    public NBTCompound getCompound(@Nonnull String key);

    @Nullable
    public NBTList getList(@Nonnull String key);

    // ===== TYPE-SPECIFIC SETTERS =====

    public void putByte(@Nonnull String key, byte value);
    public void putShort(@Nonnull String key, short value);
    public void putInt(@Nonnull String key, int value);
    public void putLong(@Nonnull String key, long value);
    public void putFloat(@Nonnull String key, float value);
    public void putDouble(@Nonnull String key, double value);
    public void putString(@Nonnull String key, @Nonnull String value);
    public void putByteArray(@Nonnull String key, @Nonnull byte[] value);
    public void putIntArray(@Nonnull String key, @Nonnull int[] value);
    public void putLongArray(@Nonnull String key, @Nonnull long[] value);
    public void putCompound(@Nonnull String key, @Nonnull NBTCompound value);
    public void putList(@Nonnull String key, @Nonnull NBTList value);

    // ===== UTILITY =====

    public boolean contains(@Nonnull String key);
    public boolean contains(@Nonnull String key, int tagType);
    public void remove(@Nonnull String key);

    @Nonnull
    public Set<String> getKeys();

    public int size();
    public boolean isEmpty();

    @Nonnull
    public NBTCompound copy();

    @Nonnull
    public NBTCompound merge(@Nonnull NBTCompound other);
}

/**
 * NBT tag types.
 */
public interface NBTTag {
    int TAG_END = 0;
    int TAG_BYTE = 1;
    int TAG_SHORT = 2;
    int TAG_INT = 3;
    int TAG_LONG = 4;
    int TAG_FLOAT = 5;
    int TAG_DOUBLE = 6;
    int TAG_BYTE_ARRAY = 7;
    int TAG_STRING = 8;
    int TAG_LIST = 9;
    int TAG_COMPOUND = 10;
    int TAG_INT_ARRAY = 11;
    int TAG_LONG_ARRAY = 12;

    int getType();

    @Nonnull
    NBTTag copy();
}

/**
 * NBT list tag.
 */
public class NBTList implements NBTTag, Iterable<NBTTag> {
    private final List<NBTTag> tags;
    private final int elementType;

    public NBTList(int elementType);

    public int size();
    public boolean isEmpty();

    public void add(@Nonnull NBTTag tag);
    public void add(int index, @Nonnull NBTTag tag);

    @Nullable
    public NBTTag get(int index);

    @Nullable
    public NBTTag remove(int index);

    public void set(int index, @Nonnull NBTTag tag);

    public int getElementType();

    // Type-specific getters
    public byte getByte(int index);
    public short getShort(int index);
    public int getInt(int index);
    public long getLong(int index);
    public float getFloat(int index);
    public double getDouble(int index);

    @Nonnull
    public String getString(int index);

    @Nullable
    public NBTCompound getCompound(int index);

    @Nullable
    public NBTList getList(int index);
}

9. Asset System

Package: com.hypixel.hytale.assetstore Total Files: ~50

The asset system manages game resources including models, textures, sounds, and data-driven content.

9.1 Asset Registry

package com.hypixel.hytale.assetstore;

import java.util.Collection;
import java.util.Optional;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Central registry for all game assets.
 */
public class AssetRegistry {
    /**
     * Get asset by ID.
     * @param id Asset identifier
     * @param type Asset class
     * @return Asset or null
     */
    @Nullable
    public <T extends Asset> T getAsset(
        @Nonnull String id, @Nonnull Class<T> type);

    /**
     * Get asset as Optional.
     * @param id Asset identifier
     * @param type Asset class
     * @return Optional with asset
     */
    @Nonnull
    public <T extends Asset> Optional<T> getOptional(
        @Nonnull String id, @Nonnull Class<T> type);

    /**
     * Get all assets of type.
     * @param type Asset class
     * @return Collection of assets
     */
    @Nonnull
    public <T extends Asset> Collection<T> getAllAssets(@Nonnull Class<T> type);

    /**
     * Register asset.
     * @param id Asset identifier
     * @param asset Asset instance
     */
    public void registerAsset(@Nonnull String id, @Nonnull Asset asset);

    /**
     * Register asset loader.
     * @param type Asset class
     * @param loader Asset loader
     */
    public <T extends Asset> void registerLoader(
        @Nonnull Class<T> type, @Nonnull AssetLoader<T> loader);

    /**
     * Load all assets from pack.
     * @param pack Asset pack
     */
    public void loadPack(@Nonnull AssetPack pack);

    /**
     * Unload asset pack.
     * @param pack Asset pack
     */
    public void unloadPack(@Nonnull AssetPack pack);

    /**
     * Reload all assets.
     */
    public void reload();

    /**
     * Register reload listener.
     * @param listener Called when assets reload
     */
    public void addReloadListener(@Nonnull Consumer<AssetRegistry> listener);
}

9.2 Asset Types

package com.hypixel.hytale.assetstore;

/**
 * Base class for all assets.
 */
public abstract class Asset {
    protected final String id;
    protected final AssetPack pack;

    protected Asset(@Nonnull String id, @Nonnull AssetPack pack) {
        this.id = id;
        this.pack = pack;
    }

    @Nonnull
    public String getId() { return id; }

    @Nonnull
    public AssetPack getPack() { return pack; }
}

/**
 * Block type definition.
 */
public class BlockAsset extends Asset {
    private final String name;
    private final Map<String, Object> properties;
    private final BlockModel model;
    private final BlockBehavior behavior;
    private final float hardness;
    private final float resistance;
    private final String[] tags;

    // Properties
    public String getName();
    public BlockModel getModel();
    public BlockBehavior getBehavior();
    public float getHardness();
    public float getResistance();
    public String[] getTags();
    public boolean hasTag(String tag);

    @Nullable
    public Object getProperty(String key);
}

/**
 * Item type definition.
 */
public class ItemAsset extends Asset {
    private final String name;
    private final ItemModel model;
    private final int maxStackSize;
    private final int maxDurability;
    private final ItemRarity rarity;
    private final String[] tags;

    // Properties...
}

/**
 * Entity type definition.
 */
public class EntityAsset extends Asset {
    private final String name;
    private final EntityModel model;
    private final Map<String, Object> attributes;
    private final String[] components;
    private final String aiController;
    private final BoundingBox hitbox;

    // Properties...
}

/**
 * Sound asset.
 */
public class SoundAsset extends Asset {
    private final String path;
    private final float volume;
    private final float pitch;
    private final boolean streaming;
    private final SoundCategory category;

    // Properties...
}

/**
 * Particle definition.
 */
public class ParticleAsset extends Asset {
    private final String texture;
    private final int frameCount;
    private final float frameTime;
    private final ParticleEmitter emitter;

    // Properties...
}

/**
 * Recipe definition.
 */
public class RecipeAsset extends Asset {
    private final RecipeType type;
    private final Object[] pattern;
    private final Map<Character, ItemStack> ingredients;
    private final ItemStack result;

    // Properties...
}

9.3 Asset Pack

package com.hypixel.hytale.assetstore;

import java.nio.file.Path;
import java.util.Collection;
import javax.annotation.Nonnull;

/**
 * Container for related assets (e.g., mod content).
 */
public class AssetPack {
    private final String id;
    private final String name;
    private final String version;
    private final String description;
    private final String[] authors;
    private final Path root;
    private final int priority;

    /**
     * @return Pack identifier (namespace)
     */
    @Nonnull
    public String getId() { return id; }

    /**
     * @return Display name
     */
    @Nonnull
    public String getName() { return name; }

    /**
     * @return Version string
     */
    @Nonnull
    public String getVersion() { return version; }

    /**
     * @return Pack description
     */
    @Nonnull
    public String getDescription() { return description; }

    /**
     * @return Author list
     */
    @Nonnull
    public String[] getAuthors() { return authors; }

    /**
     * @return Root directory
     */
    @Nonnull
    public Path getRoot() { return root; }

    /**
     * @return Load priority (higher = loaded first)
     */
    public int getPriority() { return priority; }

    /**
     * Get all asset files of type.
     * @param type Asset type path (e.g., "blocks", "items")
     * @return Collection of asset files
     */
    @Nonnull
    public Collection<Path> getAssetFiles(@Nonnull String type);
}

9.4 Asset Loader

package com.hypixel.hytale.assetstore;

import java.nio.file.Path;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Loader for specific asset types.
 */
public interface AssetLoader<T extends Asset> {
    /**
     * Load asset from file.
     * @param pack Containing pack
     * @param path File path
     * @return Loaded asset or null
     */
    @Nullable
    T load(@Nonnull AssetPack pack, @Nonnull Path path);

    /**
     * Load asset from JSON.
     * @param pack Containing pack
     * @param id Asset ID
     * @param json JSON data
     * @return Loaded asset or null
     */
    @Nullable
    T loadFromJson(@Nonnull AssetPack pack, @Nonnull String id, @Nonnull JsonObject json);

    /**
     * @return File extension for this asset type
     */
    @Nonnull
    String getExtension();

    /**
     * @return Directory name for this asset type
     */
    @Nonnull
    String getDirectory();
}

10. Codec & Serialization

Package: com.hypixel.hytale.codec Total Files: 165

The codec system provides flexible serialization for BSON, JSON, and binary formats.

10.1 Codec Interface

package com.hypixel.hytale.codec;

import javax.annotation.Nonnull;

/**
 * Bidirectional codec for serialization/deserialization.
 * @param <T> Type being encoded/decoded
 */
public interface Codec<T> {
    /**
     * Encode value to builder.
     * @param value Value to encode
     * @param builder Output builder
     */
    void encode(@Nonnull T value, @Nonnull Builder builder);

    /**
     * Decode value from reader.
     * @param reader Input reader
     * @return Decoded value
     */
    @Nonnull
    T decode(@Nonnull Reader reader);

    /**
     * @return Type description for errors
     */
    @Nonnull
    String getTypeDescription();

    /**
     * Create codec with default value.
     * @param defaultValue Default when missing
     * @return Codec with default
     */
    @Nonnull
    default Codec<T> withDefault(@Nonnull T defaultValue) {
        return new DefaultCodec<>(this, defaultValue);
    }

    /**
     * Create optional codec.
     * @return Codec returning Optional
     */
    @Nonnull
    default Codec<Optional<T>> optional() {
        return new OptionalCodec<>(this);
    }

    /**
     * Create list codec.
     * @return Codec for List of T
     */
    @Nonnull
    default Codec<List<T>> listOf() {
        return new ListCodec<>(this);
    }

    /**
     * Create map codec with string keys.
     * @return Codec for Map of String to T
     */
    @Nonnull
    default Codec<Map<String, T>> mapOf() {
        return new MapCodec<>(this);
    }
}

10.2 Primitive Codecs

package com.hypixel.hytale.codec;

/**
 * Built-in codecs for primitive types.
 */
public final class Codecs {
    public static final Codec<Boolean> BOOL = new BoolCodec();
    public static final Codec<Byte> BYTE = new ByteCodec();
    public static final Codec<Short> SHORT = new ShortCodec();
    public static final Codec<Integer> INT = new IntCodec();
    public static final Codec<Long> LONG = new LongCodec();
    public static final Codec<Float> FLOAT = new FloatCodec();
    public static final Codec<Double> DOUBLE = new DoubleCodec();
    public static final Codec<String> STRING = new StringCodec();
    public static final Codec<UUID> UUID = new UUIDCodec();

    public static final Codec<byte[]> BYTE_ARRAY = new ByteArrayCodec();
    public static final Codec<int[]> INT_ARRAY = new IntArrayCodec();
    public static final Codec<long[]> LONG_ARRAY = new LongArrayCodec();
    public static final Codec<float[]> FLOAT_ARRAY = new FloatArrayCodec();
    public static final Codec<double[]> DOUBLE_ARRAY = new DoubleArrayCodec();

    public static final Codec<Vector3i> VECTOR3I = new Vector3iCodec();
    public static final Codec<Vector3f> VECTOR3F = new Vector3fCodec();
    public static final Codec<Vector3d> VECTOR3D = new Vector3dCodec();

    public static final Codec<NBTCompound> NBT = new NBTCodec();

    private Codecs() {}
}

10.3 Builder Codec

package com.hypixel.hytale.codec;

import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnull;

/**
 * Codec using builder pattern for complex objects.
 * @param <T> Type being built
 */
public class BuilderCodec<T> implements Codec<T> {
    private final Supplier<Builder<T>> builderSupplier;
    private final Function<T, Encoder> encoder;
    private final Field<T, ?>[] fields;

    public BuilderCodec(
        @Nonnull Supplier<Builder<T>> builderSupplier,
        @Nonnull Function<T, Encoder> encoder,
        @Nonnull Field<T, ?>... fields);

    /**
     * Define field for builder codec.
     * @param name Field name
     * @param codec Field codec
     * @param getter Value getter
     * @param setter Builder setter
     * @return Field definition
     */
    @Nonnull
    public static <T, F> Field<T, F> field(
        @Nonnull String name,
        @Nonnull Codec<F> codec,
        @Nonnull Function<T, F> getter,
        @Nonnull BiConsumer<Builder<T>, F> setter);

    /**
     * Define optional field.
     */
    @Nonnull
    public static <T, F> Field<T, F> optionalField(
        @Nonnull String name,
        @Nonnull Codec<F> codec,
        @Nonnull Function<T, Optional<F>> getter,
        @Nonnull BiConsumer<Builder<T>, F> setter);

    /**
     * Define field with default value.
     */
    @Nonnull
    public static <T, F> Field<T, F> fieldWithDefault(
        @Nonnull String name,
        @Nonnull Codec<F> codec,
        @Nonnull F defaultValue,
        @Nonnull Function<T, F> getter,
        @Nonnull BiConsumer<Builder<T>, F> setter);

    /**
     * Builder interface.
     */
    public interface Builder<T> {
        @Nonnull
        T build();
    }
}

10.4 Record Codec

package com.hypixel.hytale.codec;

/**
 * Codec for Java record types using reflection.
 * @param <T> Record type
 */
public class RecordCodec<T extends Record> implements Codec<T> {
    private final Class<T> recordClass;
    private final RecordComponent[] components;
    private final Constructor<T> constructor;

    public RecordCodec(@Nonnull Class<T> recordClass);

    /**
     * Create codec for record class.
     * @param recordClass Record type
     * @return Record codec
     */
    @Nonnull
    public static <T extends Record> RecordCodec<T> of(@Nonnull Class<T> recordClass) {
        return new RecordCodec<>(recordClass);
    }
}

// Example usage
public record PlayerStats(
    int health,
    int maxHealth,
    int level,
    float experience
) {}

Codec<PlayerStats> STATS_CODEC = RecordCodec.of(PlayerStats.class);

10.5 Enum Codec

package com.hypixel.hytale.codec;

/**
 * Codec for enum types.
 */
public class EnumCodec<E extends Enum<E>> implements Codec<E> {
    private final Class<E> enumClass;
    private final boolean useOrdinal;

    /**
     * Create codec using enum names.
     */
    @Nonnull
    public static <E extends Enum<E>> EnumCodec<E> byName(@Nonnull Class<E> enumClass) {
        return new EnumCodec<>(enumClass, false);
    }

    /**
     * Create codec using ordinal values.
     */
    @Nonnull
    public static <E extends Enum<E>> EnumCodec<E> byOrdinal(@Nonnull Class<E> enumClass) {
        return new EnumCodec<>(enumClass, true);
    }
}

10.6 BSON Serialization

package com.hypixel.hytale.codec.bson;

import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.Nonnull;

/**
 * BSON (Binary JSON) serialization.
 */
public class BsonSerializer {
    /**
     * Serialize to BSON bytes.
     * @param value Value to serialize
     * @param codec Value codec
     * @return BSON bytes
     */
    @Nonnull
    public static <T> byte[] serialize(@Nonnull T value, @Nonnull Codec<T> codec);

    /**
     * Serialize to output stream.
     * @param value Value to serialize
     * @param codec Value codec
     * @param output Output stream
     */
    public static <T> void serialize(
        @Nonnull T value, @Nonnull Codec<T> codec, @Nonnull OutputStream output);

    /**
     * Deserialize from BSON bytes.
     * @param bytes BSON data
     * @param codec Value codec
     * @return Deserialized value
     */
    @Nonnull
    public static <T> T deserialize(@Nonnull byte[] bytes, @Nonnull Codec<T> codec);

    /**
     * Deserialize from input stream.
     * @param input Input stream
     * @param codec Value codec
     * @return Deserialized value
     */
    @Nonnull
    public static <T> T deserialize(@Nonnull InputStream input, @Nonnull Codec<T> codec);
}

10.7 JSON Serialization

package com.hypixel.hytale.codec.json;

import javax.annotation.Nonnull;

/**
 * JSON serialization utilities.
 */
public class JsonSerializer {
    /**
     * Serialize to JSON string.
     * @param value Value to serialize
     * @param codec Value codec
     * @return JSON string
     */
    @Nonnull
    public static <T> String toJson(@Nonnull T value, @Nonnull Codec<T> codec);

    /**
     * Serialize to pretty JSON string.
     * @param value Value to serialize
     * @param codec Value codec
     * @return Pretty-printed JSON
     */
    @Nonnull
    public static <T> String toPrettyJson(@Nonnull T value, @Nonnull Codec<T> codec);

    /**
     * Deserialize from JSON string.
     * @param json JSON string
     * @param codec Value codec
     * @return Deserialized value
     */
    @Nonnull
    public static <T> T fromJson(@Nonnull String json, @Nonnull Codec<T> codec);

    /**
     * Deserialize from JsonObject.
     * @param json JSON object
     * @param codec Value codec
     * @return Deserialized value
     */
    @Nonnull
    public static <T> T fromJson(@Nonnull JsonObject json, @Nonnull Codec<T> codec);
}

11. Math Library

Package: com.hypixel.hytale.math Total Files: 95

Comprehensive math library for vectors, matrices, quaternions, and geometric operations.

11.1 Vector Types

Vector2f

package com.hypixel.hytale.math;

/**
 * 2D float vector.
 */
public class Vector2f {
    public float x, y;

    public Vector2f();
    public Vector2f(float x, float y);
    public Vector2f(Vector2f other);

    // Arithmetic
    public Vector2f add(Vector2f other);
    public Vector2f add(float x, float y);
    public Vector2f sub(Vector2f other);
    public Vector2f mul(float scalar);
    public Vector2f mul(Vector2f other);
    public Vector2f div(float scalar);
    public Vector2f negate();

    // Geometry
    public float length();
    public float lengthSquared();
    public float distance(Vector2f other);
    public float distanceSquared(Vector2f other);
    public Vector2f normalize();
    public float dot(Vector2f other);

    // Interpolation
    public Vector2f lerp(Vector2f other, float t);

    // Utilities
    public Vector2f set(float x, float y);
    public Vector2f set(Vector2f other);
    public Vector2f zero();
    public Vector2f copy();

    public float[] toArray();
}

Vector3f

package com.hypixel.hytale.math;

/**
 * 3D float vector.
 */
public class Vector3f {
    public float x, y, z;

    public static final Vector3f ZERO = new Vector3f(0, 0, 0);
    public static final Vector3f ONE = new Vector3f(1, 1, 1);
    public static final Vector3f UP = new Vector3f(0, 1, 0);
    public static final Vector3f DOWN = new Vector3f(0, -1, 0);
    public static final Vector3f NORTH = new Vector3f(0, 0, -1);
    public static final Vector3f SOUTH = new Vector3f(0, 0, 1);
    public static final Vector3f EAST = new Vector3f(1, 0, 0);
    public static final Vector3f WEST = new Vector3f(-1, 0, 0);

    public Vector3f();
    public Vector3f(float x, float y, float z);
    public Vector3f(Vector3f other);
    public Vector3f(Vector3d other);

    // Arithmetic
    public Vector3f add(Vector3f other);
    public Vector3f add(float x, float y, float z);
    public Vector3f sub(Vector3f other);
    public Vector3f mul(float scalar);
    public Vector3f mul(Vector3f other);
    public Vector3f div(float scalar);
    public Vector3f negate();

    // Geometry
    public float length();
    public float lengthSquared();
    public float distance(Vector3f other);
    public float distanceSquared(Vector3f other);
    public Vector3f normalize();
    public float dot(Vector3f other);
    public Vector3f cross(Vector3f other);
    public float angle(Vector3f other);

    // Interpolation
    public Vector3f lerp(Vector3f other, float t);
    public Vector3f slerp(Vector3f other, float t);

    // Transformations
    public Vector3f rotate(Quaternionf rotation);
    public Vector3f rotateX(float angle);
    public Vector3f rotateY(float angle);
    public Vector3f rotateZ(float angle);
    public Vector3f transform(Matrix4f matrix);

    // Utilities
    public Vector3f set(float x, float y, float z);
    public Vector3f set(Vector3f other);
    public Vector3f zero();
    public Vector3f copy();
    public Vector3f floor();
    public Vector3f ceil();
    public Vector3f round();
    public Vector3f abs();
    public Vector3f min(Vector3f other);
    public Vector3f max(Vector3f other);
    public Vector3f clamp(Vector3f min, Vector3f max);

    public Vector3d toDouble();
    public Vector3i toInt();
    public float[] toArray();
}

Vector3d

package com.hypixel.hytale.math;

/**
 * 3D double precision vector.
 */
public class Vector3d {
    public double x, y, z;

    public static final Vector3d ZERO = new Vector3d(0, 0, 0);
    public static final Vector3d ONE = new Vector3d(1, 1, 1);

    public Vector3d();
    public Vector3d(double x, double y, double z);
    public Vector3d(Vector3d other);
    public Vector3d(Vector3f other);

    // Same methods as Vector3f but with double precision
    public Vector3d add(Vector3d other);
    public Vector3d sub(Vector3d other);
    public Vector3d mul(double scalar);
    public Vector3d div(double scalar);
    public Vector3d negate();

    public double length();
    public double lengthSquared();
    public double distance(Vector3d other);
    public double distanceSquared(Vector3d other);
    public Vector3d normalize();
    public double dot(Vector3d other);
    public Vector3d cross(Vector3d other);

    public Vector3d lerp(Vector3d other, double t);

    public Vector3f toFloat();
    public Vector3i toInt();
    public double[] toArray();
}

Vector3i

package com.hypixel.hytale.math;

/**
 * 3D integer vector (for block positions).
 */
public class Vector3i {
    public int x, y, z;

    public static final Vector3i ZERO = new Vector3i(0, 0, 0);
    public static final Vector3i ONE = new Vector3i(1, 1, 1);

    public Vector3i();
    public Vector3i(int x, int y, int z);
    public Vector3i(Vector3i other);

    // Arithmetic
    public Vector3i add(Vector3i other);
    public Vector3i add(int x, int y, int z);
    public Vector3i sub(Vector3i other);
    public Vector3i mul(int scalar);
    public Vector3i negate();

    // Geometry
    public double length();
    public int lengthSquared();
    public double distance(Vector3i other);
    public int distanceSquared(Vector3i other);
    public int manhattanDistance(Vector3i other);

    // Directions
    public Vector3i north();  // z - 1
    public Vector3i south();  // z + 1
    public Vector3i east();   // x + 1
    public Vector3i west();   // x - 1
    public Vector3i up();     // y + 1
    public Vector3i down();   // y - 1
    public Vector3i offset(Direction direction);
    public Vector3i offset(Direction direction, int amount);

    // Utilities
    public Vector3i set(int x, int y, int z);
    public Vector3i set(Vector3i other);
    public Vector3i copy();
    public Vector3i abs();
    public Vector3i min(Vector3i other);
    public Vector3i max(Vector3i other);

    public Vector3f toFloat();
    public Vector3d toDouble();
    public int[] toArray();

    // Block position utilities
    public int getChunkX();
    public int getChunkZ();
    public int getSectionY();
    public int getLocalX();
    public int getLocalZ();

    /**
     * Pack to long for storage.
     */
    public long asLong();

    /**
     * Unpack from long.
     */
    public static Vector3i fromLong(long packed);
}

Vector4f

package com.hypixel.hytale.math;

/**
 * 4D float vector (for homogeneous coordinates and colors).
 */
public class Vector4f {
    public float x, y, z, w;

    public Vector4f();
    public Vector4f(float x, float y, float z, float w);
    public Vector4f(Vector3f xyz, float w);
    public Vector4f(Vector4f other);

    // Arithmetic
    public Vector4f add(Vector4f other);
    public Vector4f sub(Vector4f other);
    public Vector4f mul(float scalar);
    public Vector4f div(float scalar);

    // Geometry
    public float length();
    public float lengthSquared();
    public Vector4f normalize();
    public float dot(Vector4f other);

    // Utilities
    public Vector3f xyz();
    public Vector4f set(float x, float y, float z, float w);
    public Vector4f copy();
    public float[] toArray();
}

11.2 Matrix Types

Matrix3f

package com.hypixel.hytale.math;

/**
 * 3x3 float matrix for rotations and 2D transforms.
 */
public class Matrix3f {
    // Row-major storage: m[row][col]
    public float m00, m01, m02;
    public float m10, m11, m12;
    public float m20, m21, m22;

    public Matrix3f();
    public Matrix3f(Matrix3f other);

    // Factory methods
    public static Matrix3f identity();
    public static Matrix3f rotation(float angle);
    public static Matrix3f rotationX(float angle);
    public static Matrix3f rotationY(float angle);
    public static Matrix3f rotationZ(float angle);
    public static Matrix3f scale(float sx, float sy, float sz);

    // Operations
    public Matrix3f mul(Matrix3f other);
    public Vector3f transform(Vector3f v);
    public Matrix3f transpose();
    public Matrix3f invert();
    public float determinant();

    // Utilities
    public Matrix3f set(Matrix3f other);
    public Matrix3f identity();
    public Matrix3f copy();
    public float[] toArray();
}

Matrix4f

package com.hypixel.hytale.math;

/**
 * 4x4 float matrix for 3D transforms.
 */
public class Matrix4f {
    // Row-major storage
    public float m00, m01, m02, m03;
    public float m10, m11, m12, m13;
    public float m20, m21, m22, m23;
    public float m30, m31, m32, m33;

    public Matrix4f();
    public Matrix4f(Matrix4f other);

    // Factory methods
    public static Matrix4f identity();
    public static Matrix4f translation(float x, float y, float z);
    public static Matrix4f translation(Vector3f v);
    public static Matrix4f rotation(Quaternionf q);
    public static Matrix4f rotationX(float angle);
    public static Matrix4f rotationY(float angle);
    public static Matrix4f rotationZ(float angle);
    public static Matrix4f scale(float sx, float sy, float sz);
    public static Matrix4f scale(float s);

    // Projection matrices
    public static Matrix4f perspective(float fov, float aspect, float near, float far);
    public static Matrix4f orthographic(float left, float right, float bottom, float top,
                                        float near, float far);
    public static Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up);

    // Operations
    public Matrix4f mul(Matrix4f other);
    public Vector3f transformPosition(Vector3f v);
    public Vector3f transformDirection(Vector3f v);
    public Vector4f transform(Vector4f v);
    public Matrix4f transpose();
    public Matrix4f invert();
    public float determinant();

    // Decomposition
    public Vector3f getTranslation();
    public Quaternionf getRotation();
    public Vector3f getScale();

    // Utilities
    public Matrix4f set(Matrix4f other);
    public Matrix4f identity();
    public Matrix4f copy();
    public Matrix3f toMatrix3f();
    public float[] toArray();
}

11.3 Quaternion

package com.hypixel.hytale.math;

/**
 * Quaternion for rotation representation.
 */
public class Quaternionf {
    public float x, y, z, w;

    public static final Quaternionf IDENTITY = new Quaternionf(0, 0, 0, 1);

    public Quaternionf();
    public Quaternionf(float x, float y, float z, float w);
    public Quaternionf(Quaternionf other);

    // Factory methods
    public static Quaternionf identity();
    public static Quaternionf fromAxisAngle(Vector3f axis, float angle);
    public static Quaternionf fromAxisAngle(float ax, float ay, float az, float angle);
    public static Quaternionf fromEuler(float pitch, float yaw, float roll);
    public static Quaternionf fromEulerDegrees(float pitch, float yaw, float roll);
    public static Quaternionf fromMatrix(Matrix3f m);
    public static Quaternionf fromMatrix(Matrix4f m);
    public static Quaternionf lookRotation(Vector3f forward, Vector3f up);

    // Operations
    public Quaternionf mul(Quaternionf other);
    public Vector3f transform(Vector3f v);
    public Quaternionf conjugate();
    public Quaternionf invert();
    public Quaternionf normalize();

    // Interpolation
    public Quaternionf lerp(Quaternionf other, float t);
    public Quaternionf slerp(Quaternionf other, float t);
    public Quaternionf nlerp(Quaternionf other, float t);

    // Conversion
    public Vector3f toEuler();
    public Vector3f toEulerDegrees();
    public Matrix3f toMatrix3f();
    public Matrix4f toMatrix4f();
    public void toAxisAngle(Vector3f axis, float[] angle);

    // Utilities
    public float length();
    public float lengthSquared();
    public float dot(Quaternionf other);
    public float angle(Quaternionf other);
    public Quaternionf set(float x, float y, float z, float w);
    public Quaternionf set(Quaternionf other);
    public Quaternionf copy();

    // Direction vectors
    public Vector3f forward();
    public Vector3f up();
    public Vector3f right();
}

11.4 Geometry

BoundingBox (AABB)

package com.hypixel.hytale.math;

/**
 * Axis-Aligned Bounding Box.
 */
public class BoundingBox {
    public double minX, minY, minZ;
    public double maxX, maxY, maxZ;

    public BoundingBox();
    public BoundingBox(double minX, double minY, double minZ,
                       double maxX, double maxY, double maxZ);
    public BoundingBox(Vector3d min, Vector3d max);
    public BoundingBox(BoundingBox other);

    // Factory
    public static BoundingBox fromCenter(Vector3d center, double width, double height, double depth);
    public static BoundingBox fromBlock(Vector3i pos);

    // Properties
    public Vector3d getMin();
    public Vector3d getMax();
    public Vector3d getCenter();
    public Vector3d getSize();
    public double getWidth();
    public double getHeight();
    public double getDepth();
    public double getVolume();

    // Tests
    public boolean contains(Vector3d point);
    public boolean contains(double x, double y, double z);
    public boolean intersects(BoundingBox other);
    public boolean intersectsRay(Vector3d origin, Vector3d direction);

    // Operations
    public BoundingBox expand(double amount);
    public BoundingBox expand(double x, double y, double z);
    public BoundingBox contract(double amount);
    public BoundingBox offset(Vector3d offset);
    public BoundingBox offset(double x, double y, double z);
    public BoundingBox union(BoundingBox other);
    public BoundingBox intersection(BoundingBox other);

    // Raycast
    public RaycastResult raycast(Vector3d origin, Vector3d direction, double maxDistance);

    // Utilities
    public BoundingBox copy();
}

/**
 * Raycast hit result.
 */
public class RaycastResult {
    public final boolean hit;
    public final double distance;
    public final Vector3d point;
    public final Vector3d normal;
    public final Direction face;

    public RaycastResult(boolean hit, double distance, Vector3d point,
                        Vector3d normal, Direction face);
}

Frustum

package com.hypixel.hytale.math;

/**
 * View frustum for culling.
 */
public class Frustum {
    private final Plane[] planes = new Plane[6];

    public Frustum();
    public Frustum(Matrix4f viewProjection);

    // Update from matrices
    public void update(Matrix4f viewProjection);
    public void update(Matrix4f view, Matrix4f projection);

    // Culling tests
    public boolean containsPoint(Vector3f point);
    public boolean containsBox(BoundingBox box);
    public boolean containsSphere(Vector3f center, float radius);
    public FrustumIntersection intersectsBox(BoundingBox box);

    // Get planes
    public Plane getLeft();
    public Plane getRight();
    public Plane getBottom();
    public Plane getTop();
    public Plane getNear();
    public Plane getFar();
}

/**
 * Frustum intersection result.
 */
public enum FrustumIntersection {
    OUTSIDE,
    INTERSECT,
    INSIDE
}

Direction

package com.hypixel.hytale.math;

/**
 * Cardinal directions.
 */
public enum Direction {
    DOWN(0, -1, 0, Axis.Y),
    UP(0, 1, 0, Axis.Y),
    NORTH(0, 0, -1, Axis.Z),
    SOUTH(0, 0, 1, Axis.Z),
    WEST(-1, 0, 0, Axis.X),
    EAST(1, 0, 0, Axis.X);

    private final int x, y, z;
    private final Axis axis;
    private final Vector3i normal;

    public int getX();
    public int getY();
    public int getZ();
    public Axis getAxis();
    public Vector3i getNormal();
    public Direction getOpposite();

    // Rotation
    public Direction rotateY();
    public Direction rotateYCCW();
    public Direction rotateX();
    public Direction rotateXCCW();

    // Factory
    public static Direction fromVector(Vector3d v);
    public static Direction fromNormal(int x, int y, int z);
    public static Direction fromIndex(int index);
    public static Direction[] horizontals();
    public static Direction[] verticals();

    public enum Axis {
        X, Y, Z;

        public boolean isHorizontal();
        public boolean isVertical();
    }
}

11.5 Math Utilities

package com.hypixel.hytale.math;

/**
 * Math utility functions.
 */
public final class MathUtils {
    public static final float PI = (float) Math.PI;
    public static final float TWO_PI = PI * 2;
    public static final float HALF_PI = PI / 2;
    public static final float DEG_TO_RAD = PI / 180f;
    public static final float RAD_TO_DEG = 180f / PI;
    public static final float EPSILON = 1e-6f;

    // Clamping
    public static int clamp(int value, int min, int max);
    public static float clamp(float value, float min, float max);
    public static double clamp(double value, double min, double max);

    // Interpolation
    public static float lerp(float a, float b, float t);
    public static double lerp(double a, double b, double t);
    public static float inverseLerp(float a, float b, float value);
    public static float smoothstep(float edge0, float edge1, float x);
    public static float smootherstep(float edge0, float edge1, float x);

    // Wrapping
    public static int wrap(int value, int min, int max);
    public static float wrap(float value, float min, float max);
    public static float wrapAngle(float angle);
    public static float wrapAngleDegrees(float angle);

    // Angle functions
    public static float toRadians(float degrees);
    public static float toDegrees(float radians);
    public static float angleDifference(float a, float b);
    public static float lerpAngle(float a, float b, float t);

    // Rounding
    public static int floor(float value);
    public static int floor(double value);
    public static int ceil(float value);
    public static int ceil(double value);
    public static int round(float value);
    public static int round(double value);
    public static float fract(float value);
    public static double fract(double value);

    // Power functions
    public static boolean isPowerOfTwo(int value);
    public static int nextPowerOfTwo(int value);
    public static int previousPowerOfTwo(int value);
    public static int log2(int value);

    // Sign
    public static int sign(int value);
    public static float sign(float value);

    // Random
    public static float random();
    public static float random(float max);
    public static float random(float min, float max);
    public static int randomInt(int max);
    public static int randomInt(int min, int max);

    // Comparison
    public static boolean equals(float a, float b);
    public static boolean equals(float a, float b, float epsilon);
    public static boolean isZero(float value);
    public static boolean isZero(float value, float epsilon);

    private MathUtils() {}
}

12. Procedural Generation

Package: com.hypixel.hytale.procedurallib Total Files: 257

Comprehensive procedural generation library for terrain, structures, and content.

12.1 Noise Functions

Perlin Noise

package com.hypixel.hytale.procedurallib.noise;

/**
 * Classic Perlin noise implementation.
 */
public class PerlinNoise implements NoiseGenerator {
    private final int[] permutation;

    public PerlinNoise();
    public PerlinNoise(long seed);

    @Override
    public float noise(float x);

    @Override
    public float noise(float x, float y);

    @Override
    public float noise(float x, float y, float z);

    /**
     * Generate octaved noise.
     * @param x X coordinate
     * @param y Y coordinate
     * @param octaves Number of octaves
     * @param persistence Amplitude decay per octave
     * @return Noise value [-1, 1]
     */
    public float octaveNoise(float x, float y, int octaves, float persistence);

    public float octaveNoise(float x, float y, float z, int octaves, float persistence);
}

Simplex Noise

package com.hypixel.hytale.procedurallib.noise;

/**
 * Simplex noise (faster, fewer artifacts than Perlin).
 */
public class SimplexNoise implements NoiseGenerator {
    public SimplexNoise();
    public SimplexNoise(long seed);

    @Override
    public float noise(float x);

    @Override
    public float noise(float x, float y);

    @Override
    public float noise(float x, float y, float z);

    /**
     * 4D simplex noise.
     */
    public float noise(float x, float y, float z, float w);
}

Worley Noise (Cellular)

package com.hypixel.hytale.procedurallib.noise;

/**
 * Worley/Cellular noise for organic patterns.
 */
public class WorleyNoise implements NoiseGenerator {
    public enum DistanceFunction {
        EUCLIDEAN,
        MANHATTAN,
        CHEBYSHEV
    }

    public enum ReturnType {
        CELL_VALUE,    // Random value per cell
        DISTANCE,      // Distance to nearest point
        DISTANCE2,     // Distance to 2nd nearest
        DISTANCE_DIFF, // Difference between 1st and 2nd
        DISTANCE_ADD   // Sum of 1st and 2nd
    }

    public WorleyNoise();
    public WorleyNoise(long seed);
    public WorleyNoise(long seed, DistanceFunction distFunc, ReturnType returnType);

    @Override
    public float noise(float x, float y);

    @Override
    public float noise(float x, float y, float z);

    public void setDistanceFunction(DistanceFunction func);
    public void setReturnType(ReturnType type);
    public void setJitter(float jitter);
}

Ridged Noise

package com.hypixel.hytale.procedurallib.noise;

/**
 * Ridged multifractal noise for mountain-like features.
 */
public class RidgedNoise implements NoiseGenerator {
    private final NoiseGenerator base;

    public RidgedNoise();
    public RidgedNoise(long seed);
    public RidgedNoise(NoiseGenerator baseNoise);

    @Override
    public float noise(float x, float y);

    @Override
    public float noise(float x, float y, float z);

    /**
     * Ridged multifractal.
     * @param octaves Number of octaves
     * @param lacunarity Frequency multiplier per octave
     * @param gain Amplitude multiplier per octave
     * @param offset Ridge sharpness
     * @return Noise value [0, 1]
     */
    public float ridgedMulti(float x, float y, int octaves,
                             float lacunarity, float gain, float offset);
}

Fractal Brownian Motion

package com.hypixel.hytale.procedurallib.noise;

/**
 * Fractal Brownian Motion (fBm) noise combiner.
 */
public class FBMNoise implements NoiseGenerator {
    private final NoiseGenerator base;
    private int octaves = 6;
    private float lacunarity = 2.0f;
    private float persistence = 0.5f;

    public FBMNoise();
    public FBMNoise(NoiseGenerator baseNoise);

    public void setOctaves(int octaves);
    public void setLacunarity(float lacunarity);
    public void setPersistence(float persistence);

    @Override
    public float noise(float x, float y);

    @Override
    public float noise(float x, float y, float z);
}

Domain Warping

package com.hypixel.hytale.procedurallib.noise;

/**
 * Domain warping for more organic noise.
 */
public class DomainWarpNoise implements NoiseGenerator {
    private final NoiseGenerator base;
    private final NoiseGenerator warpNoise;
    private float warpStrength = 1.0f;

    public DomainWarpNoise(NoiseGenerator base, NoiseGenerator warp);

    public void setWarpStrength(float strength);

    @Override
    public float noise(float x, float y);

    /**
     * Multi-pass warping.
     */
    public float warpedNoise(float x, float y, int warpIterations);
}

12.2 Noise Generator Interface

package com.hypixel.hytale.procedurallib.noise;

/**
 * Base interface for noise generators.
 */
public interface NoiseGenerator {
    /**
     * 1D noise.
     * @param x X coordinate
     * @return Noise value (typically [-1, 1])
     */
    default float noise(float x) {
        return noise(x, 0);
    }

    /**
     * 2D noise.
     * @param x X coordinate
     * @param y Y coordinate
     * @return Noise value
     */
    float noise(float x, float y);

    /**
     * 3D noise.
     * @param x X coordinate
     * @param y Y coordinate
     * @param z Z coordinate
     * @return Noise value
     */
    default float noise(float x, float y, float z) {
        return noise(x, y);
    }

    /**
     * Create scaled version.
     * @param scale Coordinate scale
     * @return Scaled noise generator
     */
    default NoiseGenerator scaled(float scale) {
        return new ScaledNoise(this, scale);
    }

    /**
     * Create offset version.
     * @param offsetX X offset
     * @param offsetY Y offset
     * @return Offset noise generator
     */
    default NoiseGenerator offset(float offsetX, float offsetY) {
        return new OffsetNoise(this, offsetX, offsetY, 0);
    }

    /**
     * Create clamped version.
     * @param min Minimum output
     * @param max Maximum output
     * @return Clamped noise generator
     */
    default NoiseGenerator clamped(float min, float max) {
        return new ClampedNoise(this, min, max);
    }

    /**
     * Create remapped version.
     * @param inMin Input minimum
     * @param inMax Input maximum
     * @param outMin Output minimum
     * @param outMax Output maximum
     * @return Remapped noise generator
     */
    default NoiseGenerator remapped(float inMin, float inMax, float outMin, float outMax) {
        return new RemappedNoise(this, inMin, inMax, outMin, outMax);
    }
}

12.3 Terrain Generation

package com.hypixel.hytale.procedurallib.terrain;

/**
 * Heightmap terrain generator.
 */
public class TerrainGenerator {
    private final NoiseGenerator baseNoise;
    private final NoiseGenerator detailNoise;
    private final NoiseGenerator erosionNoise;

    public TerrainGenerator(long seed);

    /**
     * Generate height at position.
     * @param x World X
     * @param z World Z
     * @return Height value
     */
    public float getHeight(float x, float z);

    /**
     * Generate terrain column.
     * @param x World X
     * @param z World Z
     * @param heights Output array for heights
     * @param materials Output array for materials
     */
    public void generateColumn(int x, int z, float[] heights, int[] materials);

    /**
     * Generate full chunk heightmap.
     * @param chunkX Chunk X
     * @param chunkZ Chunk Z
     * @return 16x16 heightmap
     */
    public float[][] generateChunkHeightmap(int chunkX, int chunkZ);
}

/**
 * Biome-aware terrain generator.
 */
public class BiomeTerrainGenerator {
    private final BiomeProvider biomeProvider;
    private final Map<Biome, TerrainSettings> biomeSettings;

    public BiomeTerrainGenerator(long seed, BiomeProvider provider);

    public float getHeight(float x, float z);
    public float getHeight(float x, float z, Biome biome);

    public void generateChunk(Chunk chunk);
}

/**
 * Terrain settings per biome.
 */
public class TerrainSettings {
    public float baseHeight = 64;
    public float heightVariation = 32;
    public float noiseScale = 0.01f;
    public int octaves = 6;
    public float persistence = 0.5f;
    public float lacunarity = 2.0f;
}

12.4 Structure Generation

package com.hypixel.hytale.procedurallib.structure;

/**
 * Structure placement system.
 */
public class StructureGenerator {
    private final long seed;
    private final List<StructureType> structures;

    public StructureGenerator(long seed);

    /**
     * Register structure type.
     * @param structure Structure definition
     */
    public void registerStructure(StructureType structure);

    /**
     * Get structures that should generate in chunk.
     * @param chunkX Chunk X
     * @param chunkZ Chunk Z
     * @return List of structure placements
     */
    public List<StructurePlacement> getStructuresInChunk(int chunkX, int chunkZ);

    /**
     * Check if position is valid for structure.
     * @param structure Structure type
     * @param world World
     * @param x World X
     * @param y World Y
     * @param z World Z
     * @return true if valid
     */
    public boolean canPlace(StructureType structure, World world, int x, int y, int z);

    /**
     * Place structure in world.
     * @param placement Structure placement
     * @param world Target world
     */
    public void place(StructurePlacement placement, World world);
}

/**
 * Structure type definition.
 */
public class StructureType {
    private final String id;
    private final StructureTemplate template;
    private final StructurePlacementRules rules;

    public StructureType(String id, StructureTemplate template, StructurePlacementRules rules);

    public String getId();
    public StructureTemplate getTemplate();
    public StructurePlacementRules getRules();
}

/**
 * Structure placement rules.
 */
public class StructurePlacementRules {
    public int spacing = 32;           // Minimum chunks between structures
    public int separation = 8;         // Additional random separation
    public float probability = 0.5f;   // Placement probability
    public int minY = 0;               // Minimum Y level
    public int maxY = 256;             // Maximum Y level
    public Set<Biome> validBiomes;     // Allowed biomes
    public boolean requiresFlat = false;
    public int flatRadius = 4;
}

/**
 * Placed structure instance.
 */
public class StructurePlacement {
    public final StructureType type;
    public final int x, y, z;
    public final Rotation rotation;
    public final Mirror mirror;
    public final long seed;

    public BoundingBox getBounds();
}

12.5 Biome System

package com.hypixel.hytale.procedurallib.biome;

/**
 * Biome provider for terrain generation.
 */
public interface BiomeProvider {
    /**
     * Get biome at position.
     * @param x World X
     * @param y World Y
     * @param z World Z
     * @return Biome at position
     */
    Biome getBiome(int x, int y, int z);

    /**
     * Get biome noise values for blending.
     * @param x World X
     * @param z World Z
     * @return Array of biome weights
     */
    float[] getBiomeWeights(int x, int z);
}

/**
 * Multi-noise biome provider.
 */
public class MultiNoiseBiomeProvider implements BiomeProvider {
    private final NoiseGenerator temperatureNoise;
    private final NoiseGenerator humidityNoise;
    private final NoiseGenerator continentalnessNoise;
    private final NoiseGenerator erosionNoise;
    private final NoiseGenerator weirdnessNoise;
    private final BiomeMapper mapper;

    public MultiNoiseBiomeProvider(long seed, BiomeMapper mapper);

    @Override
    public Biome getBiome(int x, int y, int z);

    /**
     * Get climate values at position.
     */
    public Climate getClimate(int x, int y, int z);
}

/**
 * Climate parameters for biome selection.
 */
public class Climate {
    public float temperature;
    public float humidity;
    public float continentalness;
    public float erosion;
    public float weirdness;
    public float depth;
}

/**
 * Maps climate values to biomes.
 */
public interface BiomeMapper {
    Biome map(Climate climate);
}

12.6 Decoration

package com.hypixel.hytale.procedurallib.decoration;

/**
 * Feature decorator for terrain details.
 */
public interface FeatureDecorator {
    /**
     * Decorate chunk with feature.
     * @param chunk Target chunk
     * @param random Seeded random
     */
    void decorate(Chunk chunk, Random random);
}

/**
 * Tree generation decorator.
 */
public class TreeDecorator implements FeatureDecorator {
    private final TreeType treeType;
    private final int density;
    private final float heightVariation;

    public TreeDecorator(TreeType type, int density);

    @Override
    public void decorate(Chunk chunk, Random random);
}

/**
 * Ore generation decorator.
 */
public class OreDecorator implements FeatureDecorator {
    private final BlockState ore;
    private final BlockState[] replaceTargets;
    private final int veinSize;
    private final int veinsPerChunk;
    private final int minY;
    private final int maxY;

    public OreDecorator(BlockState ore, int veinSize, int count, int minY, int maxY);

    @Override
    public void decorate(Chunk chunk, Random random);
}

/**
 * Vegetation scatter decorator.
 */
public class ScatterDecorator implements FeatureDecorator {
    private final BlockState feature;
    private final int tries;
    private final float spreadXZ;
    private final float spreadY;

    public ScatterDecorator(BlockState feature, int tries);

    @Override
    public void decorate(Chunk chunk, Random random);
}

13. Builtin Modules

Package: com.hypixel.hytale.builtin Total Files: 1,757 Total Modules: 43

The builtin package contains core gameplay modules implementing game mechanics.

13.1 Module List

Module Package Description
ai builtin.ai AI behavior trees and pathfinding
animation builtin.animation Entity animation system
audio builtin.audio Sound and music playback
block builtin.block Block types and behaviors
camera builtin.camera Camera systems and controllers
chat builtin.chat Chat formatting and commands
combat builtin.combat Combat mechanics and damage
crafting builtin.crafting Crafting and recipes
creature builtin.creature Creature spawning and AI
day_night builtin.daynight Day/night cycle
dialogue builtin.dialogue NPC dialogue system
effect builtin.effect Status effects
entity builtin.entity Entity base classes
equipment builtin.equipment Equipment and armor
experience builtin.experience XP and leveling
faction builtin.faction Faction and reputation
farming builtin.farming Crop growth and farming
fluid builtin.fluid Water and lava physics
health builtin.health Health and regeneration
hunger builtin.hunger Food and saturation
input builtin.input Input handling
interaction builtin.interaction Entity interactions
inventory builtin.inventory Inventory management
item builtin.item Item types and stacks
lighting builtin.lighting Light propagation
loot builtin.loot Loot tables
minigame builtin.minigame Minigame framework
model builtin.model Model loading and rendering
mount builtin.mount Mountable entities
npc builtin.npc NPC behaviors
particle builtin.particle Particle systems
pathfinding builtin.pathfinding A* pathfinding
physics builtin.physics Physics simulation
player builtin.player Player entity
projectile builtin.projectile Projectile mechanics
quest builtin.quest Quest system
scoreboard builtin.scoreboard Scoreboards and objectives
spawn builtin.spawn Spawn points and respawning
structure builtin.structure Structure loading
terrain builtin.terrain Terrain generation
tool builtin.tool Tool behaviors
vehicle builtin.vehicle Vehicle mechanics
weather builtin.weather Weather effects

13.2 AI Module

package com.hypixel.hytale.builtin.ai;

/**
 * Behavior tree for AI decision making.
 */
public class BehaviorTree {
    private final BehaviorNode root;
    private final AIContext context;

    public BehaviorTree(BehaviorNode root);

    /**
     * Execute one tick of the behavior tree.
     * @param entity Controlled entity
     * @param dt Delta time
     * @return Execution result
     */
    public BehaviorResult tick(Entity entity, float dt);
}

/**
 * Base node for behavior trees.
 */
public abstract class BehaviorNode {
    public abstract BehaviorResult execute(AIContext context);
}

/**
 * Behavior execution result.
 */
public enum BehaviorResult {
    SUCCESS,
    FAILURE,
    RUNNING
}

/**
 * Composite nodes.
 */
public class SequenceNode extends BehaviorNode { /* Execute children in order */ }
public class SelectorNode extends BehaviorNode { /* Execute until one succeeds */ }
public class ParallelNode extends BehaviorNode { /* Execute all simultaneously */ }
public class RandomSelectorNode extends BehaviorNode { /* Random child selection */ }

/**
 * Decorator nodes.
 */
public class InverterNode extends BehaviorNode { /* Invert result */ }
public class RepeaterNode extends BehaviorNode { /* Repeat N times */ }
public class SucceederNode extends BehaviorNode { /* Always succeed */ }
public class UntilFailNode extends BehaviorNode { /* Repeat until failure */ }

/**
 * Action nodes.
 */
public class MoveToAction extends BehaviorNode { /* Navigate to position */ }
public class AttackAction extends BehaviorNode { /* Attack target */ }
public class FleeAction extends BehaviorNode { /* Run from threat */ }
public class IdleAction extends BehaviorNode { /* Stand idle */ }
public class WanderAction extends BehaviorNode { /* Random movement */ }
public class FollowAction extends BehaviorNode { /* Follow target */ }
public class LookAtAction extends BehaviorNode { /* Face target */ }
public class PlayAnimationAction extends BehaviorNode { /* Play animation */ }
public class WaitAction extends BehaviorNode { /* Wait duration */ }

/**
 * Condition nodes.
 */
public class HasTargetCondition extends BehaviorNode { /* Check if has target */ }
public class InRangeCondition extends BehaviorNode { /* Check distance */ }
public class HealthBelowCondition extends BehaviorNode { /* Check health threshold */ }
public class CanSeeTargetCondition extends BehaviorNode { /* Line of sight check */ }
public class IsOnGroundCondition extends BehaviorNode { /* Ground check */ }
public class TimeOfDayCondition extends BehaviorNode { /* Day/night check */ }

13.3 Combat Module

package com.hypixel.hytale.builtin.combat;

/**
 * Damage calculation and application.
 */
public class CombatSystem {
    /**
     * Apply damage to entity.
     * @param target Target entity
     * @param source Damage source
     * @param damage Damage amount
     * @return Actual damage dealt
     */
    public float damage(Entity target, DamageSource source, float damage);

    /**
     * Calculate effective damage after armor/resistance.
     * @param base Base damage
     * @param armor Armor value
     * @param resistance Damage resistance (0-1)
     * @return Final damage
     */
    public float calculateDamage(float base, float armor, float resistance);

    /**
     * Check if entity can be damaged.
     * @param entity Target entity
     * @param source Damage source
     * @return true if damageable
     */
    public boolean canDamage(Entity entity, DamageSource source);
}

/**
 * Damage source types.
 */
public enum DamageType {
    GENERIC,
    MELEE,
    RANGED,
    MAGIC,
    FIRE,
    FALL,
    DROWNING,
    EXPLOSION,
    VOID,
    STARVATION,
    THORNS,
    WITHER
}

/**
 * Damage source information.
 */
public class DamageSource {
    private final DamageType type;
    private final Entity attacker;
    private final Entity directCause;
    private final Vector3d position;
    private final boolean bypassArmor;
    private final boolean bypassInvulnerability;

    public DamageType getType();
    public Entity getAttacker();
    public Entity getDirectCause();
    public Vector3d getPosition();
    public boolean bypassesArmor();
    public boolean bypassesInvulnerability();
}

/**
 * Attack result information.
 */
public class AttackResult {
    public final boolean hit;
    public final float damageDealt;
    public final boolean critical;
    public final boolean blocked;
    public final Vector3d knockback;
}

13.4 Inventory Module

package com.hypixel.hytale.builtin.inventory;

/**
 * Item container with slots.
 */
public interface IInventory {
    /**
     * Get inventory size.
     * @return Number of slots
     */
    int getSize();

    /**
     * Get item in slot.
     * @param slot Slot index
     * @return Item stack or empty
     */
    @Nonnull
    ItemStack getItem(int slot);

    /**
     * Set item in slot.
     * @param slot Slot index
     * @param stack Item to place
     */
    void setItem(int slot, @Nonnull ItemStack stack);

    /**
     * Add item to inventory.
     * @param stack Item to add
     * @return Remainder that didn't fit
     */
    @Nonnull
    ItemStack addItem(@Nonnull ItemStack stack);

    /**
     * Remove item from inventory.
     * @param stack Item to remove
     * @return Actually removed
     */
    @Nonnull
    ItemStack removeItem(@Nonnull ItemStack stack);

    /**
     * Check if inventory contains item.
     * @param stack Item to check
     * @return true if contains
     */
    boolean contains(@Nonnull ItemStack stack);

    /**
     * Clear all items.
     */
    void clear();

    /**
     * @return true if inventory is empty
     */
    boolean isEmpty();
}

/**
 * Player inventory with equipment slots.
 */
public class PlayerInventory implements IInventory {
    public static final int HOTBAR_SIZE = 9;
    public static final int MAIN_SIZE = 27;
    public static final int ARMOR_SIZE = 4;
    public static final int OFFHAND_SIZE = 1;

    public ItemStack getMainHand();
    public ItemStack getOffHand();
    public ItemStack getHelmet();
    public ItemStack getChestplate();
    public ItemStack getLeggings();
    public ItemStack getBoots();

    public int getSelectedSlot();
    public void setSelectedSlot(int slot);
}

/**
 * Immutable item stack.
 */
public final class ItemStack {
    public static final ItemStack EMPTY = new ItemStack();

    private final Item item;
    private final int count;
    private final NBTCompound nbt;

    public ItemStack();
    public ItemStack(Item item);
    public ItemStack(Item item, int count);
    public ItemStack(Item item, int count, NBTCompound nbt);

    public Item getItem();
    public int getCount();
    public NBTCompound getNBT();

    public boolean isEmpty();
    public boolean isStackable();
    public int getMaxStackSize();

    public ItemStack copy();
    public ItemStack withCount(int count);
    public ItemStack withNBT(NBTCompound nbt);

    public ItemStack split(int amount);
    public ItemStack merge(ItemStack other);

    public boolean isSameItem(ItemStack other);
    public boolean isSameItemSameNBT(ItemStack other);
}

13.5 Loot Module

package com.hypixel.hytale.builtin.loot;

/**
 * Loot table for random item generation.
 */
public class LootTable {
    private final String id;
    private final List<LootPool> pools;

    /**
     * Generate loot from table.
     * @param context Generation context
     * @return Generated items
     */
    public List<ItemStack> generateLoot(LootContext context);
}

/**
 * Pool of loot entries with conditions.
 */
public class LootPool {
    private final List<LootEntry> entries;
    private final List<LootCondition> conditions;
    private final NumberProvider rolls;
    private final NumberProvider bonusRolls;

    public List<ItemStack> generate(LootContext context);
}

/**
 * Single loot entry.
 */
public abstract class LootEntry {
    protected final int weight;
    protected final int quality;
    protected final List<LootCondition> conditions;
    protected final List<LootFunction> functions;

    public abstract List<ItemStack> generate(LootContext context);
}

/**
 * Entry types.
 */
public class ItemEntry extends LootEntry { /* Single item */ }
public class TagEntry extends LootEntry { /* Items from tag */ }
public class TableEntry extends LootEntry { /* Reference another table */ }
public class GroupEntry extends LootEntry { /* Multiple entries */ }
public class AlternativesEntry extends LootEntry { /* First matching */ }
public class EmptyEntry extends LootEntry { /* No items */ }

/**
 * Loot conditions.
 */
public interface LootCondition {
    boolean test(LootContext context);
}

public class RandomChanceCondition implements LootCondition { /* probability */ }
public class KilledByPlayerCondition implements LootCondition { /* player kill */ }
public class LootingEnchantCondition implements LootCondition { /* looting bonus */ }
public class EntityPropertiesCondition implements LootCondition { /* entity check */ }
public class LocationCheckCondition implements LootCondition { /* biome/structure */ }
public class MatchToolCondition implements LootCondition { /* tool predicate */ }
public class TableBonusCondition implements LootCondition { /* enchant bonus */ }

/**
 * Loot functions for modifying items.
 */
public interface LootFunction {
    ItemStack apply(ItemStack stack, LootContext context);
}

public class SetCountFunction implements LootFunction { /* Set stack count */ }
public class SetNBTFunction implements LootFunction { /* Set NBT data */ }
public class EnchantRandomlyFunction implements LootFunction { /* Random enchant */ }
public class EnchantWithLevelsFunction implements LootFunction { /* Level-based enchant */ }
public class SetDamageFunction implements LootFunction { /* Set durability */ }
public class SetAttributesFunction implements LootFunction { /* Set attributes */ }
public class ApplyBonusFunction implements LootFunction { /* Fortune/looting bonus */ }
public class LootingEnchantFunction implements LootFunction { /* Looting modifier */ }

14. Utility Libraries

Package: com.hypixel.hytale.common Total Files: 62

Common utilities used throughout the codebase.

14.1 Collections

package com.hypixel.hytale.common.collections;

/**
 * Thread-safe concurrent hash map optimized for reads.
 */
public class ConcurrentHashMap<K, V> {
    // Standard ConcurrentHashMap API
}

/**
 * Primitive long-to-object map (no boxing).
 */
public class Long2ObjectHashMap<V> {
    public V get(long key);
    public V put(long key, V value);
    public V remove(long key);
    public boolean containsKey(long key);
    public int size();
    public void clear();
    public void forEach(LongObjConsumer<V> consumer);
}

/**
 * Primitive int-to-object map.
 */
public class Int2ObjectHashMap<V> {
    public V get(int key);
    public V put(int key, V value);
    public V remove(int key);
    public boolean containsKey(int key);
    public int size();
}

/**
 * Object-to-int map (for indexing).
 */
public class Object2IntHashMap<K> {
    public int getInt(K key);
    public int put(K key, int value);
    public int removeInt(K key);
    public boolean containsKey(K key);
    public int defaultReturnValue();
    public void defaultReturnValue(int value);
}

/**
 * Primitive int list (no boxing).
 */
public class IntArrayList {
    public void add(int value);
    public void add(int index, int value);
    public int getInt(int index);
    public int removeInt(int index);
    public int size();
    public boolean isEmpty();
    public int[] toIntArray();
    public void clear();
    public void sort();
}

/**
 * Primitive long list.
 */
public class LongArrayList {
    public void add(long value);
    public long getLong(int index);
    public long removeLong(int index);
    public int size();
    public long[] toLongArray();
}

/**
 * Short-to-object concurrent map for event priorities.
 */
public class Short2ObjectConcurrentHashMap<V> {
    public Short2ObjectConcurrentHashMap(boolean sorted, int minKey);
    public V get(short key);
    public V put(short key, V value);
    public V remove(short key);
    public short[] keys();
}

/**
 * Object pool for reuse.
 */
public class ObjectPool<T> {
    public ObjectPool(Supplier<T> factory, int maxSize);

    public T acquire();
    public void release(T obj);
    public void clear();
    public int size();
}

/**
 * Ring buffer for fixed-size circular storage.
 */
public class RingBuffer<T> {
    public RingBuffer(int capacity);

    public void add(T element);
    public T get(int index);
    public T getOldest();
    public T getNewest();
    public int size();
    public int capacity();
    public boolean isEmpty();
    public boolean isFull();
    public void clear();
}

14.2 Threading

package com.hypixel.hytale.common.threading;

/**
 * Named thread factory.
 */
public class NamedThreadFactory implements ThreadFactory {
    public NamedThreadFactory(String namePrefix);
    public NamedThreadFactory(String namePrefix, boolean daemon);

    @Override
    public Thread newThread(Runnable r);
}

/**
 * Thread pool with monitoring.
 */
public class MonitoredThreadPool extends ThreadPoolExecutor {
    public MonitoredThreadPool(int coreSize, int maxSize, String name);

    public long getCompletedTaskCount();
    public long getActiveTaskCount();
    public long getTotalTaskCount();
    public double getAverageTaskTime();
}

/**
 * Scheduled task handle.
 */
public class ScheduledTask {
    public void cancel();
    public boolean isCancelled();
    public boolean isDone();
    public long getDelay(TimeUnit unit);
}

/**
 * Lock-free single-producer single-consumer queue.
 */
public class SPSCQueue<T> {
    public SPSCQueue(int capacity);

    public boolean offer(T element);
    public T poll();
    public T peek();
    public boolean isEmpty();
    public int size();
}

/**
 * Multiple-producer single-consumer queue.
 */
public class MPSCQueue<T> {
    public boolean offer(T element);
    public T poll();
    public void drain(Consumer<T> consumer);
}

14.3 Strings

package com.hypixel.hytale.common.string;

/**
 * String utilities.
 */
public final class StringUtils {
    /**
     * Check if string is null or empty.
     */
    public static boolean isEmpty(String s);

    /**
     * Check if string is null, empty, or whitespace only.
     */
    public static boolean isBlank(String s);

    /**
     * Join strings with delimiter.
     */
    public static String join(String delimiter, String... parts);
    public static String join(String delimiter, Collection<String> parts);

    /**
     * Split string by delimiter.
     */
    public static String[] split(String s, char delimiter);
    public static List<String> splitToList(String s, char delimiter);

    /**
     * Capitalize first letter.
     */
    public static String capitalize(String s);

    /**
     * Convert to camelCase.
     */
    public static String toCamelCase(String s);

    /**
     * Convert to snake_case.
     */
    public static String toSnakeCase(String s);

    /**
     * Truncate with ellipsis.
     */
    public static String truncate(String s, int maxLength);

    /**
     * Pad string to length.
     */
    public static String padLeft(String s, int length, char padChar);
    public static String padRight(String s, int length, char padChar);

    /**
     * Format with placeholders.
     */
    public static String format(String template, Object... args);

    private StringUtils() {}
}

14.4 IO Utilities

package com.hypixel.hytale.common.io;

/**
 * File utilities.
 */
public final class FileUtils {
    /**
     * Read file to string.
     */
    public static String readString(Path path) throws IOException;
    public static String readString(Path path, Charset charset) throws IOException;

    /**
     * Read file to bytes.
     */
    public static byte[] readBytes(Path path) throws IOException;

    /**
     * Read file lines.
     */
    public static List<String> readLines(Path path) throws IOException;

    /**
     * Write string to file.
     */
    public static void writeString(Path path, String content) throws IOException;

    /**
     * Write bytes to file.
     */
    public static void writeBytes(Path path, byte[] data) throws IOException;

    /**
     * Copy file.
     */
    public static void copy(Path source, Path target) throws IOException;

    /**
     * Delete recursively.
     */
    public static void deleteRecursively(Path path) throws IOException;

    /**
     * Create directories if not exist.
     */
    public static void ensureDirectory(Path path) throws IOException;

    /**
     * Get file extension.
     */
    public static String getExtension(Path path);

    /**
     * Get file name without extension.
     */
    public static String getBaseName(Path path);

    private FileUtils() {}
}

/**
 * Stream utilities.
 */
public final class StreamUtils {
    /**
     * Read input stream to bytes.
     */
    public static byte[] toByteArray(InputStream in) throws IOException;

    /**
     * Read input stream to string.
     */
    public static String toString(InputStream in, Charset charset) throws IOException;

    /**
     * Copy stream.
     */
    public static long copy(InputStream in, OutputStream out) throws IOException;

    /**
     * Skip exactly n bytes.
     */
    public static void skipFully(InputStream in, long n) throws IOException;

    private StreamUtils() {}
}

15. Metrics & Logging

Package: com.hypixel.hytale.metrics, com.hypixel.hytale.logger Total Files: 29

Performance monitoring and structured logging infrastructure.

15.1 Metrics System

package com.hypixel.hytale.metrics;

/**
 * Single metric measurement (timing, count, etc.).
 */
public class Metric {
    private final AtomicLong count = new AtomicLong();
    private final AtomicLong totalNanos = new AtomicLong();
    private volatile long minNanos = Long.MAX_VALUE;
    private volatile long maxNanos = Long.MIN_VALUE;

    /**
     * Record a measurement.
     * @param nanos Duration in nanoseconds
     */
    public void record(long nanos);

    /**
     * Start timing.
     * @return Timing handle
     */
    public MetricTimer start();

    /**
     * Get measurement count.
     */
    public long getCount();

    /**
     * Get total time in nanoseconds.
     */
    public long getTotalNanos();

    /**
     * Get average time in nanoseconds.
     */
    public double getAverageNanos();

    /**
     * Get minimum time.
     */
    public long getMinNanos();

    /**
     * Get maximum time.
     */
    public long getMaxNanos();

    /**
     * Reset all measurements.
     */
    public void reset();
}

/**
 * Active timer for automatic stop.
 */
public class MetricTimer implements AutoCloseable {
    private final Metric metric;
    private final long startNanos;

    public MetricTimer(Metric metric);

    /**
     * Stop timer and record measurement.
     */
    public void stop();

    @Override
    public void close() {
        stop();
    }
}

/**
 * Metrics registry for named metrics.
 */
public class MetricsRegistry {
    private final Map<String, Metric> metrics = new ConcurrentHashMap<>();

    /**
     * Get or create metric.
     * @param name Metric name
     * @return Metric instance
     */
    public Metric getMetric(String name);

    /**
     * Get all metric names.
     */
    public Set<String> getMetricNames();

    /**
     * Export metrics as map.
     */
    public Map<String, MetricSnapshot> snapshot();

    /**
     * Reset all metrics.
     */
    public void resetAll();
}

/**
 * Immutable metric snapshot.
 */
public record MetricSnapshot(
    long count,
    long totalNanos,
    double averageNanos,
    long minNanos,
    long maxNanos
) {}

15.2 Logging System

package com.hypixel.hytale.logger;

/**
 * Logger interface.
 */
public interface HytaleLogger {
    /**
     * Log trace message.
     */
    void trace(String message);
    void trace(String format, Object... args);

    /**
     * Log debug message.
     */
    void debug(String message);
    void debug(String format, Object... args);

    /**
     * Log info message.
     */
    void info(String message);
    void info(String format, Object... args);

    /**
     * Log warning message.
     */
    void warn(String message);
    void warn(String format, Object... args);
    void warn(String message, Throwable t);

    /**
     * Log error message.
     */
    void error(String message);
    void error(String format, Object... args);
    void error(String message, Throwable t);

    /**
     * Check if level is enabled.
     */
    boolean isTraceEnabled();
    boolean isDebugEnabled();
    boolean isInfoEnabled();
    boolean isWarnEnabled();
    boolean isErrorEnabled();

    /**
     * Get logger name.
     */
    String getName();
}

/**
 * Logger factory.
 */
public final class LoggerFactory {
    /**
     * Get logger for class.
     * @param clazz Class requesting logger
     * @return Logger instance
     */
    public static HytaleLogger getLogger(Class<?> clazz);

    /**
     * Get logger by name.
     * @param name Logger name
     * @return Logger instance
     */
    public static HytaleLogger getLogger(String name);

    private LoggerFactory() {}
}

/**
 * Log levels.
 */
public enum LogLevel {
    TRACE(0),
    DEBUG(1),
    INFO(2),
    WARN(3),
    ERROR(4),
    OFF(5);

    private final int level;

    public int getLevel();
    public boolean isEnabled(LogLevel threshold);
}

15.3 Logger Backend

package com.hypixel.hytale.logger.backend;

/**
 * Logger backend implementation.
 */
public class HytaleLoggerBackend implements HytaleLogger {
    private final String name;
    private final LogOutput output;
    private volatile LogLevel level = LogLevel.INFO;

    public HytaleLoggerBackend(String name, LogOutput output);

    /**
     * Set minimum log level.
     */
    public void setLevel(LogLevel level);

    /**
     * Get current log level.
     */
    public LogLevel getLevel();
}

/**
 * Log output destination.
 */
public interface LogOutput {
    /**
     * Write log entry.
     * @param entry Log entry
     */
    void write(LogEntry entry);

    /**
     * Flush buffered entries.
     */
    void flush();

    /**
     * Close output.
     */
    void close();
}

/**
 * Console log output.
 */
public class ConsoleLogOutput implements LogOutput {
    private final boolean colorEnabled;

    public ConsoleLogOutput();
    public ConsoleLogOutput(boolean colorEnabled);

    @Override
    public void write(LogEntry entry);
}

/**
 * File log output with rotation.
 */
public class FileLogOutput implements LogOutput {
    private final Path directory;
    private final String filePrefix;
    private final long maxFileSize;
    private final int maxFiles;

    public FileLogOutput(Path directory, String filePrefix);
    public FileLogOutput(Path directory, String filePrefix, long maxSize, int maxFiles);

    @Override
    public void write(LogEntry entry);
}

/**
 * Log entry data.
 */
public record LogEntry(
    long timestamp,
    LogLevel level,
    String loggerName,
    String message,
    Throwable throwable,
    String threadName
) {}

/**
 * Log formatters.
 */
public interface LogFormatter {
    String format(LogEntry entry);
}

public class SimpleLogFormatter implements LogFormatter {
    // [LEVEL] [Logger] Message
}

public class DetailedLogFormatter implements LogFormatter {
    // [timestamp] [LEVEL] [thread] [logger] message
}

public class JsonLogFormatter implements LogFormatter {
    // {"timestamp":..., "level":..., "logger":..., "message":...}
}

16. Function Interfaces

Package: com.hypixel.hytale.function Total Files: 34

Functional interfaces for callbacks and event handlers.

16.1 Core Functions

package com.hypixel.hytale.function;

/**
 * Supplier with checked exception.
 */
@FunctionalInterface
public interface ThrowingSupplier<T, E extends Exception> {
    T get() throws E;
}

/**
 * Consumer with checked exception.
 */
@FunctionalInterface
public interface ThrowingConsumer<T, E extends Exception> {
    void accept(T t) throws E;
}

/**
 * Function with checked exception.
 */
@FunctionalInterface
public interface ThrowingFunction<T, R, E extends Exception> {
    R apply(T t) throws E;
}

/**
 * BiConsumer with checked exception.
 */
@FunctionalInterface
public interface ThrowingBiConsumer<T, U, E extends Exception> {
    void accept(T t, U u) throws E;
}

/**
 * BiFunction with checked exception.
 */
@FunctionalInterface
public interface ThrowingBiFunction<T, U, R, E extends Exception> {
    R apply(T t, U u) throws E;
}

/**
 * Runnable with checked exception.
 */
@FunctionalInterface
public interface ThrowingRunnable<E extends Exception> {
    void run() throws E;
}

16.2 Primitive Functions

package com.hypixel.hytale.function;

/**
 * Int consumer (no boxing).
 */
@FunctionalInterface
public interface IntConsumer {
    void accept(int value);
}

/**
 * Long consumer.
 */
@FunctionalInterface
public interface LongConsumer {
    void accept(long value);
}

/**
 * Float consumer.
 */
@FunctionalInterface
public interface FloatConsumer {
    void accept(float value);
}

/**
 * Double consumer.
 */
@FunctionalInterface
public interface DoubleConsumer {
    void accept(double value);
}

/**
 * Int supplier.
 */
@FunctionalInterface
public interface IntSupplier {
    int getAsInt();
}

/**
 * Long supplier.
 */
@FunctionalInterface
public interface LongSupplier {
    long getAsLong();
}

/**
 * Float supplier.
 */
@FunctionalInterface
public interface FloatSupplier {
    float getAsFloat();
}

/**
 * Int to object function.
 */
@FunctionalInterface
public interface IntFunction<R> {
    R apply(int value);
}

/**
 * Object to int function.
 */
@FunctionalInterface
public interface ToIntFunction<T> {
    int applyAsInt(T value);
}

/**
 * Int to int function.
 */
@FunctionalInterface
public interface IntUnaryOperator {
    int applyAsInt(int operand);
}

/**
 * Int binary operator.
 */
@FunctionalInterface
public interface IntBinaryOperator {
    int applyAsInt(int left, int right);
}

/**
 * Long to object consumer.
 */
@FunctionalInterface
public interface LongObjConsumer<T> {
    void accept(long key, T value);
}

/**
 * Int to object consumer.
 */
@FunctionalInterface
public interface IntObjConsumer<T> {
    void accept(int key, T value);
}

16.3 Specialized Functions

package com.hypixel.hytale.function;

/**
 * Tri-consumer.
 */
@FunctionalInterface
public interface TriConsumer<T, U, V> {
    void accept(T t, U u, V v);
}

/**
 * Tri-function.
 */
@FunctionalInterface
public interface TriFunction<T, U, V, R> {
    R apply(T t, U u, V v);
}

/**
 * Quad-consumer.
 */
@FunctionalInterface
public interface QuadConsumer<T, U, V, W> {
    void accept(T t, U u, V v, W w);
}

/**
 * Boolean supplier.
 */
@FunctionalInterface
public interface BooleanSupplier {
    boolean getAsBoolean();
}

/**
 * Object and float consumer.
 */
@FunctionalInterface
public interface ObjFloatConsumer<T> {
    void accept(T obj, float value);
}

/**
 * Object and int consumer.
 */
@FunctionalInterface
public interface ObjIntConsumer<T> {
    void accept(T obj, int value);
}

/**
 * Object and long consumer.
 */
@FunctionalInterface
public interface ObjLongConsumer<T> {
    void accept(T obj, long value);
}

17. Complete Class Reference

This section provides a categorized index of all ~7,100+ classes in the Hytale Server API.

17.1 Package Summary

Package Classes Description
com.hypixel.hytale.assetstore ~50 Asset loading and management
com.hypixel.hytale.builtin 1,757 Core gameplay modules
com.hypixel.hytale.codec 165 Serialization framework
com.hypixel.hytale.common 62 Shared utilities
com.hypixel.hytale.component ~100 ECS implementation
com.hypixel.hytale.event 23 Event bus system
com.hypixel.hytale.function 34 Functional interfaces
com.hypixel.hytale.logger 17 Logging framework
com.hypixel.hytale.math 95 Math library
com.hypixel.hytale.metrics 12 Performance monitoring
com.hypixel.hytale.plugin.early 3 Plugin loader
com.hypixel.hytale.procedurallib 257 Procedural generation
com.hypixel.hytale.protocol 737 Network protocol
com.hypixel.hytale.registry 3 Registration framework
com.hypixel.hytale.server 3,807 Server implementation
com.hypixel.hytale.storage ~20 Persistence layer

17.2 Key Entry Points

Server Bootstrap

Plugin Development

Entity System

Networking

Assets

World

Player

17.3 Architecture Overview

┌──────────────────────────────────────────────────────────────┐
                        HytaleServer                          
├──────────────────────────────────────────────────────────────┤
  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐ 
   Universe   EventBus   AssetReg   PacketRegistry   
  └────┬────┘  └────┬────┘  └────┬────┘  └────────┬────────┘ 
                                                          
  ┌────▼────────────▼────────────▼─────────────────▼────┐    
                      World(s)                             
    ┌─────────────────────────────────────────────┐       
                  Entity Store (ECS)                     
      ┌─────────┐ ┌─────────┐ ┌─────────────────┐│       
      Component Component  Archetype Chunks││       
       Registry   Types      (SoA Layout)  ││       
      └─────────┘ └─────────┘ └─────────────────┘│       
    └─────────────────────────────────────────────┘       
                                                           
    ┌──────────┐  ┌──────────┐  ┌──────────────────┐      
      Chunks     Entities    Ticking Systems        
     (16x384x      (Ref)     (EntityTicking,        
       16)                    RefSystem, etc)       
    └──────────┘  └──────────┘  └──────────────────┘      
  └─────────────────────────────────────────────────────┘    
                                                              
  ┌─────────────────┐  ┌─────────────────────────────────┐   
   Player Sessions         Network (QUIC + Zstd)         
   ┌─────────────┐     ┌────────┐  ┌────────────────┐    
      Player          Packets   Binary Codec       
     Inventory   │◄─┼──│ (268)     (VarInt, NBT)      
     Abilities       └────────┘  └────────────────┘    
   └─────────────┘   └─────────────────────────────────┘   
  └─────────────────┘                                         
                                                              
  ┌──────────────────────────────────────────────────────┐   
                     Builtin Modules                        
    ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐          
      AI   Combat  Loot  Quest  Physics ...      
    └──────┘ └──────┘ └──────┘ └──────┘ └──────┘          
  └──────────────────────────────────────────────────────┘   
                                                              
  ┌──────────────────────────────────────────────────────┐   
                  Early Plugin System                       
    ┌───────────────┐  ┌───────────────────────────────┐│   
    ClassTransformer   TransformingClassLoader      ││   
     (ASM bytecode)    (Secure package protection)  ││   
    └───────────────┘  └───────────────────────────────┘│   
  └──────────────────────────────────────────────────────┘   
└──────────────────────────────────────────────────────────────┘

Quick Reference: Server Events

| ShutdownEvent | server | Void | Server shutting down | | PlayerConnectEvent | universe | Void | Player connecting | | PlayerDisconnectEvent | universe | Void | Player disconnecting | | ChunkPreLoadProcessEvent | storage | Void | Before chunk loading | | ChunkSaveEvent | storage | Void | Before chunk saving | | ChunkUnloadEvent | storage | Void | Before chunk unloading | | EntityRemoveEvent | entity | Void | Entity being removed | | LoadAssetEvent | asset | Void | Asset validation phase | | RegisterAssetStoreEvent | assetstore | Void | Asset store registered | | RemoveAssetStoreEvent | assetstore | Void | Asset store removed | | LoadedAssetsEvent | assetstore | Class | Assets loaded | | GenerateAssetsEvent | assetstore | Class | Dynamic asset generation |


Quick Reference: Entity Components

Component Description
TransformComponent Position and rotation
VelocityComponent Movement velocity
BoundingBox Collision hitbox
InvulnerableComponent Damage immunity
CollisionResultComponent Physics results
RespondToHitComponent Hit reaction behavior
NonSerialized Prevent serialization
NonTicking Prevent system processing

Quick Reference: Packet Categories

Category ID Range Description
Connection 0-9 Handshake, ping/pong
Authentication 10-19 Auth, password
World Init 20-39 World settings, assets
Asset Updates 40-99 Asset configuration
Player 100-119 Movement, interaction
World State 131-159 Chunks, blocks, time
Entities 160-179 Entity updates, inventory
UI/Windows 200-234 Windows, chat, lists
World Map 240-245 Map data
Camera 280-294 Camera, interactions
Asset Editor 300-361 Editor operations
Builder Tools 400-423 Creative building