Class SpawningContext

java.lang.Object
com.hypixel.hytale.server.spawning.SpawningContext

public class SpawningContext extends Object
SpawningContext is used to provide and return information for spatial spawning tests.
  • Field Details

    • xBlock

      public int xBlock
      The X coordinate of the block column being considered for spawning, relative to the chunk.
    • zBlock

      public int zBlock
      The Z coordinate of the block column being considered for spawning, relative to the chunk.
    • ySpawnHint

      public double ySpawnHint
      The Y coordinate hint for spawning, used to find spawn spans in the column.
    • groundLevel

      public int groundLevel
      The ground level at the current (x,z) position.

      Used for spawn position calculations and as the basis for ySpawnMin.

    • groundBlockId

      public int groundBlockId
      The block ID of the ground block at the current (x,z) position.

      Used for spawn position calculations and safe spawning checks.

    • groundRotation

      public int groundRotation
      The rotation index of the ground block at the current (x,z) position.
    • groundBlockType

      @Nullable public BlockType groundBlockType
      The block type of the ground block at the current (x,z) position, or null if the block type could not be resolved.
    • groundFluidId

      public int groundFluidId
      The fluid ID of the ground fluid at the current (x,z) position, or -1 if there is no fluid or if the fluid ID could not be resolved.
    • groundFluid

      @Nullable public Fluid groundFluid
      The fluid asset of the ground fluid at the current (x,z) position, or null if there is no fluid or if the fluid asset could not be resolved.
    • movementMode

      @Nullable public MovementMode movementMode
      The movement mode of the NPC being spawned, used for safe spawning checks and to determine which blocks are valid for spawning.
    • enableSafeSpawning

      public boolean enableSafeSpawning
      Determines whether safe spawning checks should be performed when selecting spawn positions, such as checking for breathable air blocks for the NPC's movement mode.
    • activeMotionControllerType

      @Nullable public String activeMotionControllerType
      The type of motion controller active for the NPC being spawned.

      Used to determine whether certain spawn positions are valid based on the motion controller's requirements (e.g. water for swim controller).

    • ySpanMin

      public double ySpanMin
      The minimum world Y coordinate of the spawn span selected for spawning, inclusive.
    • ySpanMax

      public double ySpanMax
      The maximum world Y coordinate of the spawn span selected for spawning, exclusive.
    • yBlock

      public int yBlock
      The height of the world chunk at the current (x,z) position.

      Used for validating that spawn spans are within the world height limits.

    • waterLevel

      public int waterLevel
      The current water level in the spawn span, or Integer.MAX_VALUE if there is no water.
    • airHeight

      public int airHeight
      The height of the bottommost air block over water or solid, or Integer.MAX_VALUE if the span has no air boundary.
    • ySpawnMin

      public double ySpawnMin
    • xSpawn

      public double xSpawn
    • zSpawn

      public double zSpawn
    • ySpawn

      public double ySpawn
    • rotation

      @Nonnull public final Rotation3f rotation
      The rotation of the spawn position; only initialized when the world is set.

      Initialized with a random yaw and zero pitch/roll in commonInit(); can be adjusted before spawning.

    • breathesInAir

      public boolean breathesInAir
      Determines whether the spawnable can breathe in air, used for safe spawning checks when movement mode requires air.

      Initialized to true but should be set by setSpawnable(ISpawnableWithModel).

    • breathesInWater

      public boolean breathesInWater
      Determines whether the spawnable can breathe in water, used for safe spawning checks when movement mode requires water.
    • invalidMaterials

      public int invalidMaterials
      The cached invalid-material mask for position validation.

      Computed from movement mode on first use and used to check if the spawn position is valid for the current movement mode.

      Reset in releaseFull() to ensure it is recalculated for the next spawn attempt with potentially different movement mode.

    • swimDepth

      public double swimDepth
      The cached swim depth for dive spawning, computed from model and spawnable parameters on first use.

      Reset in releaseFull() to ensure it is recalculated for the next spawn attempt with potentially different model or spawnable parameters.

  • Constructor Details

    • SpawningContext

      public SpawningContext()
      Default Constructor for a SpawningContext instance.
  • Method Details

    • setResult

      public boolean setResult(@Nonnull SpawningContext.Result result)
      Sets the detailed result for the current operation.
      Parameters:
      result - The SpawningContext.Result to store.
      Returns:
      true if result is SpawningContext.Result.OK, or false otherwise.
    • getLastResult

      @Nonnull public SpawningContext.Result getLastResult()
      Gets the detailed result from the last operation.
      Returns:
      The last SpawningContext.Result.
    • getMinSpawnSpanHeight

      public double getMinSpawnSpanHeight()
      Returns:
      the minimum span height required for the current model, or positive infinity if no model is set
    • getAvailableSpanHeightAtHint

      public double getAvailableSpanHeightAtHint()
      Returns:
      the height of a too-short span at ySpawnHint, or Double.NaN if none was recorded
    • clearResult

      public void clearResult()
      Resets the detailed result to SpawningContext.Result.OK. Call this method before an operation that does not return a boolean.
    • setSpawnable

      public boolean setSpawnable(@Nonnull ISpawnableWithModel spawnable)
      Set spawnable and model for overlap checking
      Parameters:
      spawnable - The spawnable to set
      Returns:
      true if spawnable and model initialized
    • setSpawnable

      public boolean setSpawnable(@Nonnull ISpawnableWithModel spawnable, boolean maxScale)
      Set spawnable and model for overlap checking.
      Parameters:
      spawnable - The spawnable to set.
      maxScale - Whether to force the model to be max scale so it ensures all scales can fit.
      Returns:
      true if spawnable and model initialized, false if there was an error initializing either the spawnable or the model.
    • newModel

      public void newModel()
      Create a new model as clone from existing one.
    • getModel

      @Nullable public Model getModel()
      Returns:
      the model used in collision checks, or null if no model is set
    • getSpawnMovementModes

      @Nonnull public Set<MovementMode> getSpawnMovementModes()
      Query the movement modes the spawnable can spawn with.

      These are the default movement modes of the spawnable, reduced to the modes that are safe to spawn in. The result is cached until the spawnable changes. An empty result is not cached, so a failed query is repeated.

      Do not modify the returned set.

      Returns:
      the movement modes to spawn with, empty if no default mode of the spawnable is safe to spawn in
    • setMovementMode

      public boolean setMovementMode(MovementMode movementMode, boolean safeSpawning)
      Set desired movement mode to be used to spawn next NPC.
      Parameters:
      movementMode - The movement mode to pick spawn position for.
      safeSpawning - If true ensure that NPC isn't spawned where it violates concerns like breathing (Default true).
      Returns:
      true if the movement mode was set successfully, or false if it is incompatible or no spawnable is set.
    • setEnvironmentChunk

      public void setEnvironmentChunk(@Nonnull World world, @Nonnull Ref<ChunkStore> chunkRef, @Nonnull WorldChunk worldChunk, int environmentIndex)
      Bind this context to a chunk and the environment to spawn into. This method stores environmentIndex for later column searches. Call setEnvironmentColumn(int, int, SuppressionSpanHelper) after this to filter candidate positions by that environment.
      Parameters:
      world - The world the chunk lives in.
      chunkRef - The chunk entity reference for the chunk being searched.
      worldChunk - The WorldChunk component of that chunk.
      environmentIndex - The environment to look for spawning into or AssetMapWithIndexes.NOT_FOUND if spawn at position.
    • setColumn

      public boolean setColumn(int x, int z, int yHint, @Nonnull int[] yRange)
      Choose column position relative to chunk for spawning without taking environment into account. This method does not read environment runs or use the stored environment index. It resets the stored environment index to AssetMapWithIndexes.NOT_FOUND.
      Parameters:
      x - The column position relative to chunk.
      z - The column position relative to chunk.
      yHint - A hint value for the y height.
      yRange - An array representing the downwards and upwards range to find columns in relative to the yHint (e.g. [ -1, 10 ] is one below and ten above.
      Returns:
      true if any spawning spans were created, false if no valid blocks were found in the column or chunk components were missing.
    • setColumn

      public boolean setColumn(int x, int z, int yHint, @Nonnull int[] yRange, @Nonnull SuppressionSpanHelper suppressionHelper)
      Choose column position relative to chunk for spawning without taking environment into account but with spawn suppression. This method does not read environment runs or use the stored environment index. It resets the stored environment index to AssetMapWithIndexes.NOT_FOUND.
      Parameters:
      x - The column position relative to chunk.
      z - The column position relative to chunk.
      yHint - A hint value for the y height.
      yRange - An array representing the downwards and upwards range to find columns in relative to the yHint (e.g. [ -1, 10 ] is one below and ten above.
      suppressionHelper - A helper object which adjusts ranges based on which spans the selected role cannot spawn in.
      Returns:
      true if any spawning spans were created, false if no valid blocks were found in the column or chunk components were missing.
    • setEnvironmentColumn

      public boolean setEnvironmentColumn(int x, int z, @Nonnull SuppressionSpanHelper suppressionHelper)
      Choose a column in the chunk from setEnvironmentChunk(World, Ref, WorldChunk, int). This method reads environment runs and samples only runs that match the stored environment index. Spawn suppression is applied to matching environment runs.
      Parameters:
      x - The column position relative to chunk.
      z - The column position relative to chunk.
      suppressionHelper - A helper object which adjusts ranges based on which spans the selected role cannot spawn in.
      Returns:
      true if any spawning spans were created, or false if none were created or chunk components were missing.
    • getModifierScope

      @Nullable public Scope getModifierScope()
    • getWorld

      @Nullable public World getWorld()
      Returns:
      the World this context is bound to, or null if the context has not been bound to a chunk yet or has been released.
    • getChunkRef

      @Nullable public Ref<ChunkStore> getChunkRef()
      Returns:
      the chunk-entity reference this context is bound to, or null if the context has not been bound to a chunk yet or has been released.
    • getSectionRefAtBlockY

      @Nullable public Ref<ChunkStore> getSectionRefAtBlockY(int y)
      Resolve the chunk-section reference of the bound column at the given block Y.

      The section is resolved per call rather than cached on this context, because selecting a spawn span moves yBlock across section boundaries within a single spawn attempt.

      Parameters:
      y - The world-space block Y coordinate.
      Returns:
      the chunk-section reference, or null if the context is not bound to a chunk or the section is not loaded.
    • getChunkComponentStore

      @Nullable public ComponentAccessor<ChunkStore> getChunkComponentStore()
      Returns:
      the chunk-store component accessor for this context's bound chunk, or null if the context has not been bound to a chunk yet or has been released.
    • computeBlockTopPenetrationDepth

      public double computeBlockTopPenetrationDepth(@Nonnull World world, @Nonnull org.joml.Vector3dc position, int maxSearchHeight)
      Determine how deep a position is below the first empty block within a bounded upward search.
      Parameters:
      world - The world
      position - The world position to check.
      maxSearchHeight - Maximum number of blocks to search above the position.
      Returns:
      The depth below the resolved block surface, a value greater than maxSearchHeight if no surface was found, or Double.NEGATIVE_INFINITY if required world data is unavailable.
    • checkColumnBelow

      @Nonnull public SpawningContext.ColumnBelowState checkColumnBelow(@Nonnull World world, @Nonnull org.joml.Vector3dc position)
      Determine whether every block below a world position is empty.
      Parameters:
      world - The world
      position - The world position above the column to check.
      Returns:
      The state of the column, including whether the required world data is available.
    • set

      public boolean set(@Nonnull World world, double x, double y, double z)
      Initialize world and position. This variant should be used when spawning NPC outside the spawning module.

      This method searches within the default vertical offset from y. It does not use the stored environment index and resets it.

      On success the resolved chunk entity reference, world, and chunk-store accessor are stored on this context so subsequent calls (e.g. canSpawn(boolean, boolean)) need not be passed them. All three are cleared by release().

      Parameters:
      world - The world to probe.
      x - The position.
      y - The position hint to find span.
      z - The position.
      Returns:
      true if the chunk is loaded, ticking, and a span was found; false if the chunk is not loaded/ticking, components are missing, or no valid span exists at the position.
    • set

      public boolean set(@Nonnull World world, double x, double y, double z, boolean requireSpanAtY)
      Initialize world and position. This variant should be used when spawning NPC outside the spawning module.

      This method searches within the default vertical offset from y. It does not use the stored environment index and resets it.

      On success the resolved chunk entity reference, world, and chunk-store accessor are stored on this context so subsequent calls (e.g. canSpawn(boolean, boolean)) need not be passed them. All three are cleared by release().

      Parameters:
      world - The world to probe.
      x - The position.
      y - The position hint to find span.
      z - The position.
      requireSpanAtY - When true, only a span that contains y is accepted. When false, the closest span is used.
      Returns:
      true if the chunk is loaded, ticking, and a span was found; false if the chunk is not loaded/ticking, components are missing, or no valid span exists at the position.
    • set

      public boolean set(@Nonnull World world, double x, double y, double z, boolean requireSpanAtY, double maxVerticalOffset)
      Initialize world and position within a bounded vertical distance.
      Parameters:
      world - The world to probe.
      x - The position.
      y - The position hint to find span.
      z - The position.
      requireSpanAtY - When true, only a span that contains y is accepted.
      maxVerticalOffset - The maximum distance to search above or below y.
      Returns:
      true if the chunk is loaded, ticking, and a span was found; false otherwise.
    • set

      public boolean set(@Nonnull World world, double x, double y, double z, boolean requireSpanAtY, double maxDownwardOffset, double maxUpwardOffset)
      Initialize world and position within asymmetric bounded vertical distances.
      Parameters:
      world - The world to probe.
      x - The position.
      y - The position hint to find span.
      z - The position.
      requireSpanAtY - When true, only a span that contains y is accepted.
      maxDownwardOffset - The maximum distance to search below y.
      maxUpwardOffset - The maximum distance to search above y.
      Returns:
      true if the chunk is loaded, ticking, and a span was found; false otherwise.
    • setExact

      public boolean setExact(@Nonnull World world, double x, double y, double z)
      Initialize world and an exact spawn position for direct overlap validation. This variant preserves the supplied world position instead of selecting a nearby spawn span in the column.

      This method does not read environment runs or use the stored environment index. It resets the stored environment index to AssetMapWithIndexes.NOT_FOUND.

      On success the resolved chunk entity reference, world, and chunk-store accessor are stored on this context so subsequent calls (e.g. validatePosition(int)) need not be passed them. All three are cleared by release().

      Parameters:
      world - The world to probe.
      x - The exact spawn x coordinate.
      y - The exact spawn y coordinate.
      z - The exact spawn z coordinate.
      Returns:
      true if the chunk is loaded and ticking, false otherwise.
    • setExactWithSurroundings

      public boolean setExactWithSurroundings(@Nonnull World world, double x, double y, double z, boolean hasSupport, @Nonnull SpawnPositionPlacement placement, double waterDepth, boolean bodyTouchingLiquid, boolean requiresWading, boolean eyeInAir, boolean eyeInLiquid)
      Set an exact position and replace default surroundings queries with caller-provided data. This method does not read environment runs or use the stored environment index. It resets the stored environment index to AssetMapWithIndexes.NOT_FOUND.
      Parameters:
      world - The target world.
      x - The exact candidate X coordinate.
      y - The exact candidate Y coordinate.
      z - The exact candidate Z coordinate.
      hasSupport - Whether the candidate has proven solid support.
      placement - How the exact position is placed.
      waterDepth - The available water depth below the exact position.
      bodyTouchingLiquid - Whether liquid overlaps the candidate body.
      requiresWading - Whether the candidate fluid depth requires wading.
      eyeInAir - Whether the candidate eye is in air.
      eyeInLiquid - Whether the candidate eye is in liquid.
      Returns:
      true when the surroundings were set, or false when its chunk is unavailable.
    • hasPositionSurroundings

      public boolean hasPositionSurroundings()
    • hasPositionValidationResult

      public boolean hasPositionValidationResult()
    • getPositionValidationResult

      public int getPositionValidationResult()
    • isPositionValidationOnGround

      public boolean isPositionValidationOnGround()
    • isBodyTouchingLiquid

      public boolean isBodyTouchingLiquid()
    • requiresWading

      public boolean requiresWading()
    • deleteCurrentSpawnSpan

      public void deleteCurrentSpawnSpan()
      Remove spawn span selected previously by selectRandomSpawnSpan or selectSpawnSpan.
    • selectRandomSpawnSpan

      public boolean selectRandomSpawnSpan()
      Choose a random empty/fluid span of blocks in a column for spawning.
      Returns:
      true if a spawn span was selected, false if no spawn spans are available or if chunk components were missing.
    • canSpawn

      @Nonnull public SpawnTestResult canSpawn(boolean testOverlapBlocks, boolean testOverlapEntities)
      Determine if an NPC could spawn at a given location.
      Parameters:
      testOverlapBlocks - Whether to perform test if NPC would be stuck in blocks/level geometry.
      testOverlapEntities - Whether to perform test if NPC would be intersecting with another entity.
      Returns:
      RESULT code; SpawnTestResult.TEST_OK if no overlaps detected.
    • canSpawn

      @Nonnull public SpawnTestResult canSpawn()
      Determine if an NPC could spawn at a given location, performing both block and entity overlap tests.
      Returns:
      RESULT code; SpawnTestResult.TEST_OK if no overlaps detected.
    • canSpawnOnBlock

      public boolean canSpawnOnBlock(@Nullable it.unimi.dsi.fastutil.ints.IntSet spawnBlockSet, int spawnFluidTag)
      Check if the NPC is allowed to spawn in a fluid or on a solid block.

      This test only checks for the fluid type at top of water column.

      Parameters:
      spawnBlockSet - The allowed block types the NPC can spawn on.
      spawnFluidTag - The allowed fluids the NPC can spawn in.
      Returns:
      true NPC can spawn on the given blocks or in the fluids, false if not.
    • isWaterBlock

      public static boolean isWaterBlock(int fluidId)
      Check if block is fluid or submerged.
      Parameters:
      fluidId - The fluid id.
      Returns:
      true if block is fluid or submerged, false if block is empty or solid.
    • getWaterLevel

      public int getWaterLevel()
      Get water depth at current location of spawning context.
      Returns:
      the water depth in blocks.
    • getAirHeight

      public int getAirHeight()
      Get height of first empty block for location of spawning context.
      Returns:
      the y coordinate of empty block.
    • isInsideSpan

      public boolean isInsideSpan(double y)
      Test if computed y is inside current span. The span covers [ySpanMin, ySpanMax).
      Returns:
      true if y is inside current span, false otherwise.
    • isInWater

      public boolean isInWater(float minDepth)
      Determine if position is underwater.

      Will adjust ySpawn position to ensure entity is submerged.

      Parameters:
      minDepth - Required depth underwater for entity, rounded up to whole blocks.
      Returns:
      true if spawning position is valid for diving NPC, false if not underwater or not deep enough.
    • isOnSolidGround

      public boolean isOnSolidGround()
      Determine if position is not underwater. Will adjust ySpawn to ensure entity is on surface.
      Returns:
      true if spawning position is valid for walking NPC, false otherwise.
    • isInAir

      public boolean isInAir(double height)
      Determine if position is in air.

      Will adjust ySpawn position to ensure entity is above surface.

      Parameters:
      height - The desired height of the entity above the lowest air block. A negative value counts as zero.
      Returns:
      true if spawning position is valid for flying NPC, false otherwise.
    • validatePosition

      public boolean validatePosition(int invalidMaterials)
      Check if bounding box would overlap with level blocks of given materials.
      Parameters:
      invalidMaterials - material of blocks NPC is not allowed to overlap with.
      Returns:
      true if NPC at position would not overlap with geometry, false otherwise.
    • validatePosition

      public boolean validatePosition(int invalidMaterials, boolean cubeBlockersOnly)
      Parameters:
      cubeBlockersOnly - When true, only full-cube blocks block the position; partial models (ropes, plants, cocoons, etc.) are ignored. Used for mid-air spawns that emerge from decorative non-cube blocks.
    • canBreathe

      public boolean canBreathe(boolean breathesInAir, boolean breathesInWater)
      Determines whether an NPC with given breathing capabilities could spawn at the current position of this context without suffocating.
      Parameters:
      breathesInAir - Whether the NPC can breathe in air.
      breathesInWater - Whether the NPC can breathe in water.
      Returns:
      true if the NPC can breathe at the current position, false if it would suffocate.
    • release

      public void release()
      Clear any per-attempt scratch state held by this context.
    • releaseFull

      public void releaseFull()
      Clear any references spawning context holds.
    • buildMovementModeWeights

      @Nullable public static double[] buildMovementModeWeights(@Nullable Map<MovementMode, Double> userWeights, @Nonnull Set<MovementMode> supportedMovementModes, @Nonnull Set<MovementMode> defaultMovementModes, @Nullable Set<MovementMode> safeMovementModes)
      Compute movement mode weights into a new array without modifying this context.

      Returns the result as a freshly allocated double[]. Returns null when all weights are zero.

      Parameters:
      userWeights - The optional user-configured per-mode weights from RoleSpawnParameters.
      supportedMovementModes - The supported movement modes returned by ISpawnable.getMovementModes(SpawningContext, Set, Set, Set).
      defaultMovementModes - The default spawn movement modes returned by ISpawnable.getMovementModes(SpawningContext, Set, Set, Set).
      safeMovementModes - The optional set of movement modes the NPC can use safely; when non-null any mode absent from this set is zeroed out.
      Returns:
      a new weight array, or null if all weights are zero.
    • getExecutionContext

      @Nonnull public ExecutionContext getExecutionContext()
      Returns:
      the execution context instance of this spawning context.
    • newPosition

      @Nonnull public org.joml.Vector3d newPosition()
      Returns:
      the position vector of the spawn position.
    • newRotation

      @Nonnull public Rotation3f newRotation()
      Returns:
      the rotation of the spawn position as a new Rotation3f with (pitch, yaw, roll) in radians.
    • toString

      @Nonnull public String toString()
      Overrides:
      toString in class Object