First commit

This commit is contained in:
Arigadam 2026-10-12 10:23:10 +00:00
commit 9b0fe9b1b7
126 changed files with 31043 additions and 0 deletions

111
cubiomes/__init__.py Normal file
View file

@ -0,0 +1,111 @@
"""cubiomes — Python bindings for the cubiomes Minecraft world-generation library.
Quick-start example::
from cubiomes import Generator, MCVersion, Dimension, BiomeID
g = Generator(MCVersion.MC_1_21)
g.apply_seed(Dimension.DIM_OVERWORLD, 123456789)
biome = g.get_biome_at(0, 63, 0)
print(f"Biome at (0, 63, 0): {BiomeID(biome).name}") # e.g. "plains"
# 256×256 biome map at 1:4 scale
ids = g.gen_biomes(-128, -128, 256, 256, scale=4)
# Locate all villages near the origin
from cubiomes import StructureType, get_structure_pos, is_viable_structure_pos
for reg_x in range(-3, 4):
for reg_z in range(-3, 4):
pos = get_structure_pos(StructureType.Village, MCVersion.MC_1_21,
123456789, reg_x, reg_z)
if pos and is_viable_structure_pos(StructureType.Village, g, *pos):
print(f"Village at {pos}")
"""
from .enums import (
MCVersion,
Dimension,
BiomeID,
StructureType,
LARGE_BIOMES,
NO_BETA_OCEAN,
FORCE_OCEAN_VARIANTS,
BF_APPROX,
BF_FORCED_OCEAN,
)
from ._wrapper import (
# Classes
Generator,
BiomeFilter,
StrongholdIterator,
StructureVariant,
# Structure functions
get_structure_config,
get_structure_pos,
is_viable_structure_pos,
is_viable_feature_biome,
get_variant,
get_mineshafts,
# Stronghold / spawn
iter_strongholds,
init_first_stronghold,
# Biome filter / search
setup_biome_filter,
# Seed / misc utilities
is_slime_chunk,
get_shadow,
move_structure,
chunk_generate_rnd,
get_population_seed,
# Biome property helpers
biome_exists,
is_overworld_biome,
get_dimension,
get_mutated,
get_category,
are_similar,
is_mesa,
is_shallow_ocean,
is_deep_ocean,
is_oceanic,
is_snowy,
)
__version__ = "0.1.0"
__author__ = "cubiomes-python contributors"
__all__ = [
# Enums / constants
"MCVersion", "Dimension", "BiomeID", "StructureType",
"LARGE_BIOMES", "NO_BETA_OCEAN", "FORCE_OCEAN_VARIANTS",
"BF_APPROX", "BF_FORCED_OCEAN",
# Classes
"Generator", "BiomeFilter", "StrongholdIterator", "StructureVariant",
# Functions
"get_structure_config",
"get_structure_pos",
"is_viable_structure_pos",
"is_viable_feature_biome",
"get_variant",
"get_mineshafts",
"iter_strongholds",
"init_first_stronghold",
"setup_biome_filter",
"is_slime_chunk",
"get_shadow",
"move_structure",
"chunk_generate_rnd",
"get_population_seed",
"biome_exists",
"is_overworld_biome",
"get_dimension",
"get_mutated",
"get_category",
"are_similar",
"is_mesa",
"is_shallow_ocean",
"is_deep_ocean",
"is_oceanic",
"is_snowy",
]

4
cubiomes/__main__.py Normal file
View file

@ -0,0 +1,4 @@
"""Entry point for ``python -m cubiomes``."""
from .search import main
import sys
sys.exit(main())

Binary file not shown.

Binary file not shown.

Binary file not shown.

196
cubiomes/_cubiomes.pxd Normal file
View file

@ -0,0 +1,196 @@
# C declarations for the cubiomes library.
# Included by _wrapper.pyx via `cimport _cubiomes`.
from libc.stdint cimport int8_t, int16_t, int32_t, int64_t
from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
from libc.stddef cimport size_t
# ─── biomes.h ────────────────────────────────────────────────────────────────
cdef extern from "biomes.h":
int biomeExists(int mc, int id) nogil
int isOverworld(int mc, int id) nogil
int getDimension(int id) nogil
int getMutated(int mc, int id) nogil
int getCategory(int mc, int id) nogil
int areSimilar(int mc, int id1, int id2) nogil
int isMesa(int id) nogil
int isShallowOcean(int id) nogil
int isDeepOcean(int id) nogil
int isOceanic(int id) nogil
int isSnowy(int id) nogil
# ─── biomenoise.h → Range ─────────────────────────────────────────────────────
cdef extern from "biomenoise.h":
ctypedef struct Range:
int scale
int x
int z
int sx
int sz
int y
int sy
# ─── generator.h ─────────────────────────────────────────────────────────────
cdef extern from "generator.h":
# Only the leading public fields are declared; the rest (large union) are
# opaque from Python's perspective but correctly sized by the C header.
ctypedef struct Generator:
int mc
int dim
uint32_t flags
uint64_t seed
uint64_t sha
void setupGenerator(Generator *g, int mc, uint32_t flags) nogil
void applySeed(Generator *g, int dim, uint64_t seed) nogil
size_t getMinCacheSize(const Generator *g, int scale,
int sx, int sy, int sz) nogil
int *allocCache(const Generator *g, Range r) nogil
int genBiomes(const Generator *g, int *cache, Range r) nogil
int getBiomeAt(const Generator *g, int scale, int x, int y, int z) nogil
# ─── finders.h ───────────────────────────────────────────────────────────────
cdef extern from "finders.h":
ctypedef struct Pos:
int x
int z
ctypedef struct Pos3:
int x
int y
int z
ctypedef struct StructureConfig:
int32_t salt
int8_t regionSize
int8_t chunkRange
uint8_t structType
int8_t dim
float rarity
ctypedef struct StrongholdIter:
Pos pos
Pos nextapprox
int index
int ringnum
int ringmax
int ringidx
double angle
double dist
uint64_t rnds
int mc
ctypedef struct StructureVariant:
uint8_t abandoned
uint8_t giant
uint8_t underground
uint8_t airpocket
uint8_t basement
uint8_t cracked
uint8_t size
uint8_t start
short biome
uint8_t rotation
uint8_t mirror
int16_t x
int16_t y
int16_t z
int16_t sx
int16_t sy
int16_t sz
ctypedef struct BiomeFilter:
uint64_t tempsToFind
uint64_t otempToFind
uint64_t majorToFind
uint64_t edgesToFind
uint64_t raresToFind
uint64_t raresToFindM
uint64_t shoreToFind
uint64_t shoreToFindM
uint64_t riverToFind
uint64_t riverToFindM
uint64_t oceanToFind
int specialCnt
uint32_t flags
uint64_t tempsToExcl
uint64_t majorToExcl
uint64_t edgesToExcl
uint64_t raresToExcl
uint64_t raresToExclM
uint64_t shoreToExcl
uint64_t shoreToExclM
uint64_t riverToExcl
uint64_t riverToExclM
uint64_t biomeToExcl
uint64_t biomeToExclM
uint64_t biomeToFind
uint64_t biomeToFindM
uint64_t biomeToPick
uint64_t biomeToPickM
# Static-inline functions (callable because finders.h is included in the
# generated C translation unit).
uint64_t moveStructure(uint64_t baseSeed, int regX, int regZ) nogil
uint64_t getShadow(uint64_t seed) nogil
int isSlimeChunk(uint64_t seed, int chunkX, int chunkZ) nogil
uint64_t chunkGenerateRnd(uint64_t worldSeed,
int chunkX, int chunkZ) nogil
Pos getFeaturePos(StructureConfig config, uint64_t seed,
int regX, int regZ) nogil
Pos getLargeStructurePos(StructureConfig config, uint64_t seed,
int regX, int regZ) nogil
# Regular exported functions
int getStructureConfig(int structureType, int mc,
StructureConfig *sconf) nogil
int getStructurePos(int structureType, int mc, uint64_t seed,
int regX, int regZ, Pos *pos) nogil
int isViableStructurePos(int structType, Generator *g,
int blockX, int blockZ, uint32_t flags) nogil
int isViableFeatureBiome(int mc, int structureType, int biomeID) nogil
int getMineshafts(int mc, uint64_t seed,
int chunkX, int chunkZ, int chunkW, int chunkH,
Pos *out, int nout) nogil
int getVariant(StructureVariant *sv, int structType, int mc,
uint64_t seed, int blockX, int blockZ, int biomeID) nogil
Pos initFirstStronghold(StrongholdIter *sh, int mc, uint64_t s48) nogil
int nextStronghold(StrongholdIter *sh, const Generator *g) nogil
Pos getSpawn(const Generator *g) nogil
Pos estimateSpawn(const Generator *g, uint64_t *rng) nogil
void setupBiomeFilter(
BiomeFilter *bf,
int mc, uint32_t flags,
const int *required, int requiredLen,
const int *excluded, int excludedLen,
const int *matchany, int matchanyLen) nogil
int checkForBiomes(
Generator *g, int *cache, Range r,
int dim, uint64_t seed,
const BiomeFilter *filter,
volatile char *stop) nogil
Pos locateBiome(
const Generator *g, int x, int y, int z, int radius,
uint64_t validB, uint64_t validM,
uint64_t *rng, int *passes) nogil
int getBiomeCenters(
Pos *pos, int *siz, int nmax,
Generator *g, Range r,
int match, int minsiz, int tol,
volatile char *stop) nogil
uint64_t getPopulationSeed(int mc, uint64_t ws, int x, int z) nogil

25450
cubiomes/_wrapper.c Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

814
cubiomes/_wrapper.pyx Normal file
View file

@ -0,0 +1,814 @@
# cython: language_level=3
# cython: boundscheck=False
# cython: wraparound=False
# cython: cdivision=True
"""
Cython wrapper around the cubiomes C library.
All public symbols are re-exported via cubiomes/__init__.py.
"""
cimport cython
cimport _cubiomes as cb
from libc.stdlib cimport malloc, free
from libc.string cimport memcpy
from libc.stdint cimport uint64_t, uint32_t, int16_t, uint8_t
from cpython.array cimport array, clone
import array as _array_module
# Reusable template for int arrays (avoids repeated Python-level construction)
cdef array _INT_TMPL = _array_module.array('i')
# ─── Generator ───────────────────────────────────────────────────────────────
cdef class Generator:
"""Minecraft biome generator.
Wraps the cubiomes ``Generator`` C struct. The instance is bound to a
specific MC version and generator flags at construction time; world seed
and dimension are applied later via :meth:`apply_seed`.
Args:
mc (int): MC version constant, e.g. ``MCVersion.MC_1_21``.
flags (int): Optional generator flags:
* ``LARGE_BIOMES = 0x1``
* ``NO_BETA_OCEAN = 0x2``
* ``FORCE_OCEAN_VARIANTS = 0x4``
Example::
from cubiomes import Generator, MCVersion, Dimension, BiomeID
g = Generator(MCVersion.MC_1_21)
g.apply_seed(Dimension.DIM_OVERWORLD, 12345)
biome = g.get_biome_at(0, 63, 0)
print(BiomeID(biome).name) # e.g. "plains"
"""
cdef cb.Generator *_g
def __cinit__(self, int mc, unsigned int flags=0):
self._g = <cb.Generator *>malloc(sizeof(cb.Generator))
if self._g is NULL:
raise MemoryError("Failed to allocate Generator")
cb.setupGenerator(self._g, mc, flags)
def __dealloc__(self):
if self._g is not NULL:
free(self._g)
self._g = NULL
def __repr__(self):
return (f"Generator(mc={self._g.mc}, dim={self._g.dim}, "
f"seed={self._g.seed})")
# ── properties ────────────────────────────────────────────────────────────
@property
def mc(self) -> int:
"""MC version this generator was set up for."""
return self._g.mc
@property
def dim(self) -> int:
"""Current dimension (0=Overworld, -1=Nether, +1=End)."""
return self._g.dim
@property
def seed(self) -> int:
"""Current world seed."""
return self._g.seed
@property
def flags(self) -> int:
"""Generator flags (LARGE_BIOMES, etc.)."""
return self._g.flags
# ── core methods ──────────────────────────────────────────────────────────
def apply_seed(self, int dim, uint64_t seed):
"""Bind a world seed and dimension to the generator.
Must be called before any biome generation.
Args:
dim (int): Dimension — use :class:`~cubiomes.Dimension` constants.
* ``DIM_OVERWORLD = 0``
* ``DIM_NETHER = -1``
* ``DIM_END = +1``
seed (int): 64-bit world seed.
"""
cb.applySeed(self._g, dim, seed)
def get_biome_at(self, int x, int y, int z, int scale=4) -> int:
"""Get the biome ID at a single position.
Args:
x (int): Block/biome X coordinate.
y (int): Vertical coordinate.
For scale=1 this is a block Y; for scale≥4 it is a 1:4 Y
(divide block Y by 4 and pass 0 for a surface check).
z (int): Block/biome Z coordinate.
scale (int): Coordinate scale — ``1`` for block-level Voronoi
sampling or ``4`` (default) for standard biome coordinates.
Returns:
int: A :class:`~cubiomes.BiomeID` value, or ``-1`` on failure.
"""
return cb.getBiomeAt(self._g, scale, x, y, z)
def gen_biomes(self, int x, int z, int sx, int sz,
int scale=4, int y=0, int sy=0):
"""Generate biomes for a rectangular (or cuboid) region.
Returns a flat :class:`array.array` of signed integers with
``sx * max(sy, 1) * sz`` elements.
**Indexing** (0-based relative indices):
* 2-D case (``sy ≤ 1``): ``result[z_i * sx + x_i]``
* 3-D case (``sy > 1``): ``result[y_i * sx * sz + z_i * sx + x_i]``
**Quick numpy conversion**::
import numpy as np
arr = np.array(g.gen_biomes(-128, -128, 256, 256), dtype=np.int32)
grid = arr.reshape(256, 256) # grid[z_index, x_index]
Args:
x (int): West edge of the region in scale units.
z (int): North edge of the region in scale units.
sx (int): Width (west→east).
sz (int): Depth (north→south).
scale (int): Sampling scale: 1, 4, 16, 64 or 256.
y (int): Vertical position (block Y if scale=1, else biome Y).
sy (int): Vertical size; values ≤ 1 produce a 2-D result.
Returns:
array.array: Flat array of biome IDs (typecode ``'i'``).
Raises:
RuntimeError: If the underlying C call fails.
MemoryError: If the biome cache could not be allocated.
"""
cdef cb.Range r
r.scale = scale
r.x = x
r.z = z
r.sx = sx
r.sz = sz
r.y = y
r.sy = sy
cdef int *cache = cb.allocCache(self._g, r)
if cache is NULL:
raise MemoryError("Failed to allocate biome cache")
cdef int ret = cb.genBiomes(self._g, cache, r)
if ret != 0:
free(cache)
raise RuntimeError(f"genBiomes failed (code {ret})")
cdef int true_sy = sy if sy > 0 else 1
cdef int total = sx * true_sy * sz
cdef array result = clone(_INT_TMPL, total, False)
memcpy(result.data.as_ints, cache, total * sizeof(int))
free(cache)
return result
def get_spawn(self):
"""Find the world spawn point.
Accurate but slow — iterates over biomes near the origin.
Returns:
tuple[int, int]: ``(x, z)`` block coordinates.
"""
cdef cb.Pos pos = cb.getSpawn(self._g)
return (pos.x, pos.z)
def estimate_spawn(self):
"""Estimate the world spawn point quickly.
Uses biome sampling without the full search.
Returns:
tuple[int, int]: ``(x, z)`` block coordinates (approximate).
"""
cdef uint64_t rng = 0
cdef cb.Pos pos = cb.estimateSpawn(self._g, &rng)
return (pos.x, pos.z)
def locate_biome(self, int x, int y, int z, int radius,
object valid_biomes):
"""Find a position with a specific biome within a search radius.
Performs a random walk over the area — may be slow for large radii.
Args:
x, y, z (int): Search origin (block coordinates).
radius (int): Half-size of the search square (in blocks).
valid_biomes: Iterable of :class:`~cubiomes.BiomeID` integers.
Returns:
tuple[int, int]: ``(x, z)`` block coordinates of a matching tile.
"""
cdef uint64_t valid_b = 0
cdef uint64_t valid_m = 0
for bid in valid_biomes:
b = int(bid)
if 0 <= b < 64:
valid_b |= (<uint64_t>1) << b
elif 128 <= b < 192:
valid_m |= (<uint64_t>1) << (b - 128)
cdef uint64_t rng = 0
cdef int passes = 0
cdef cb.Pos pos = cb.locateBiome(
self._g, x, y, z, radius, valid_b, valid_m, &rng, &passes)
return (pos.x, pos.z)
def get_biome_centers(self, int x, int z, int sx, int sz,
int match, int min_size=0, int tolerance=4,
int max_results=256):
"""Locate center positions of contiguous regions of a biome.
The area is specified at 1:4 scale (biome coordinates).
Args:
x, z (int): Top-left corner of the search area (biome coords).
sx, sz (int): Width and depth of the search area.
match (int): :class:`~cubiomes.BiomeID` to search for.
min_size (int): Minimum region size to report.
tolerance (int): Border tolerance in biome blocks.
max_results (int): Maximum number of results.
Returns:
list[tuple[int, int]]: List of ``(x, z)`` biome center positions.
"""
cdef cb.Range r
r.scale = 4
r.x = x
r.z = z
r.sx = sx
r.sz = sz
r.y = 0
r.sy = 1
cdef cb.Pos *pos_buf = <cb.Pos *>malloc(max_results * sizeof(cb.Pos))
cdef int *siz_buf = <int *>malloc(max_results * sizeof(int))
if pos_buf is NULL or siz_buf is NULL:
free(pos_buf)
free(siz_buf)
raise MemoryError()
cdef int n = cb.getBiomeCenters(
pos_buf, siz_buf, max_results,
self._g, r, match, min_size, tolerance, NULL)
result = [(pos_buf[i].x, pos_buf[i].z) for i in range(n)]
free(pos_buf)
free(siz_buf)
return result
def check_for_biomes(self, int x, int z, int sx, int sz,
int scale, int dim, uint64_t seed,
BiomeFilter biome_filter,
int y=0, int sy=1):
"""Test whether a region satisfies a biome filter.
The generator does **not** need to have ``apply_seed`` called first;
the seed and dimension are applied internally.
Args:
x, z, sx, sz (int): Region to check.
scale (int): Sampling scale (1, 4, 16, 64, 256).
dim (int): Dimension constant.
seed (int): World seed to test.
biome_filter (BiomeFilter): Filter created via
:func:`setup_biome_filter`.
y, sy (int): Vertical position and size.
Returns:
int: ``0`` = requirements not met, ``1`` = met (fully generated),
``2`` = met (partially generated).
"""
cdef cb.Range r
r.scale = scale
r.x = x
r.z = z
r.sx = sx
r.sz = sz
r.y = y
r.sy = sy
return cb.checkForBiomes(
self._g, NULL, r, dim, seed, &biome_filter._bf, NULL)
# ─── BiomeFilter ─────────────────────────────────────────────────────────────
cdef class BiomeFilter:
"""Biome requirement filter used with :meth:`Generator.check_for_biomes`.
Prefer constructing via the :func:`setup_biome_filter` helper which
accepts Python lists of :class:`~cubiomes.BiomeID` values.
Args:
mc (int): MC version.
required: Biomes that **all** must be present.
excluded: Biomes that must **not** be present.
match_any: At least **one** of these biomes must be present.
flags (int): Optional filter flags (e.g. ``BF_APPROX = 0x01``).
"""
cdef cb.BiomeFilter _bf
def __cinit__(self, int mc,
object required=None,
object excluded=None,
object match_any=None,
unsigned int flags=0):
cdef int *req_arr = NULL
cdef int *exc_arr = NULL
cdef int *any_arr = NULL
cdef int req_len = 0, exc_len = 0, any_len = 0
if required:
req_len = len(required)
req_arr = <int *>malloc(req_len * sizeof(int))
for i, v in enumerate(required):
req_arr[i] = int(v)
if excluded:
exc_len = len(excluded)
exc_arr = <int *>malloc(exc_len * sizeof(int))
for i, v in enumerate(excluded):
exc_arr[i] = int(v)
if match_any:
any_len = len(match_any)
any_arr = <int *>malloc(any_len * sizeof(int))
for i, v in enumerate(match_any):
any_arr[i] = int(v)
cb.setupBiomeFilter(
&self._bf, mc, flags,
req_arr, req_len,
exc_arr, exc_len,
any_arr, any_len)
free(req_arr)
free(exc_arr)
free(any_arr)
# ─── StrongholdIterator ───────────────────────────────────────────────────────
cdef class StrongholdIterator:
"""Iterator over all stronghold positions in generation order.
Yields accurate ``(x, z)`` block coordinate tuples obtained after biome
verification. Create via :func:`iter_strongholds`.
The generator passed at construction must be set up (via
:meth:`Generator.apply_seed`) for Overworld generation; it is used for
the biome checks needed to confirm each stronghold's exact location.
For MC ≥ 1.19.3 you can pass ``None`` to skip biome checks (approximate
positions only).
"""
cdef cb.StrongholdIter _sh
cdef Generator _gen
cdef bint _has_current
cdef bint _has_more
def __cinit__(self, Generator gen, uint64_t seed48):
self._gen = gen
cb.initFirstStronghold(&self._sh, gen.mc, seed48)
cdef int remaining = cb.nextStronghold(
&self._sh, gen._g if gen is not None else NULL)
self._has_current = True
self._has_more = (remaining > 0)
def __iter__(self):
return self
def __next__(self):
if not self._has_current:
raise StopIteration
pos = (self._sh.pos.x, self._sh.pos.z)
if self._has_more:
remaining = cb.nextStronghold(
&self._sh,
self._gen._g if self._gen is not None else NULL)
self._has_more = (remaining > 0)
else:
self._has_current = False
return pos
@property
def index(self) -> int:
"""Zero-based index of the stronghold last yielded."""
return self._sh.index
@property
def next_approx(self):
"""Approximate ``(x, z)`` of the upcoming stronghold (±112 blocks)."""
return (self._sh.nextapprox.x, self._sh.nextapprox.z)
# ─── StructureVariant ────────────────────────────────────────────────────────
cdef class StructureVariant:
"""Metadata for a structure instance (rotation, bounding box, etc.).
Obtain via :func:`get_variant`.
"""
cdef cb.StructureVariant _sv
def __repr__(self):
return (f"StructureVariant(biome={self._sv.biome}, "
f"rotation={self._sv.rotation}, "
f"pos={self.pos}, size={self.size})")
@property
def abandoned(self) -> bool:
"""True if this is a zombie/abandoned village."""
return bool(self._sv.abandoned)
@property
def giant(self) -> bool:
"""True if this is the giant ruined-portal variant."""
return bool(self._sv.giant)
@property
def underground(self) -> bool:
"""True if the structure spawns underground."""
return bool(self._sv.underground)
@property
def airpocket(self) -> bool:
"""True if the ruined portal has an air pocket."""
return bool(self._sv.airpocket)
@property
def basement(self) -> bool:
"""True if the igloo has a basement."""
return bool(self._sv.basement)
@property
def biome(self) -> int:
"""Biome variant ID used by the structure."""
return self._sv.biome
@property
def rotation(self) -> int:
"""Rotation: 0=north, 1=east, 2=south, 3=west."""
return self._sv.rotation
@property
def mirror(self) -> bool:
"""True if the structure is mirrored."""
return bool(self._sv.mirror)
@property
def pos(self):
"""``(x, y, z)`` block coordinates of the structure origin."""
return (self._sv.x, self._sv.y, self._sv.z)
@property
def size(self):
"""``(sx, sy, sz)`` bounding-box dimensions in blocks."""
return (self._sv.sx, self._sv.sy, self._sv.sz)
# ─── Module-level functions ───────────────────────────────────────────────────
def get_structure_config(int struct_type, int mc):
"""Return the configuration for a structure type in a given MC version.
Args:
struct_type (int): A :class:`~cubiomes.StructureType` constant.
mc (int): MC version constant.
Returns:
dict | None: Dictionary with keys ``salt``, ``region_size``,
``chunk_range``, ``struct_type``, ``dim``, ``rarity``; or ``None``
if the structure does not exist in that version.
"""
cdef cb.StructureConfig sc
if not cb.getStructureConfig(struct_type, mc, &sc):
return None
return {
"salt": sc.salt,
"region_size": sc.regionSize,
"chunk_range": sc.chunkRange,
"struct_type": sc.structType,
"dim": sc.dim,
"rarity": sc.rarity,
}
def get_structure_pos(int struct_type, int mc, uint64_t seed,
int reg_x, int reg_z):
"""Find the block position of a structure attempt in a region.
Minecraft divides the world into regions (size depends on structure type)
and attempts one structure per region. This returns the block position
of that attempt. Use :func:`is_viable_structure_pos` to confirm the
biome requirements are met.
Args:
struct_type (int): :class:`~cubiomes.StructureType` constant.
mc (int): MC version.
seed (int): World seed (lower 48 bits are used).
reg_x, reg_z (int): Region coordinates.
Returns:
tuple[int, int] | None: ``(x, z)`` block coordinates, or ``None``
if no valid attempt exists in this region.
"""
cdef cb.Pos pos
if not cb.getStructurePos(struct_type, mc, seed, reg_x, reg_z, &pos):
return None
return (pos.x, pos.z)
def is_viable_structure_pos(int struct_type, Generator gen,
int block_x, int block_z,
unsigned int flags=0) -> bool:
"""Check whether biomes allow a structure to generate at a position.
The generator must have ``apply_seed`` called with the correct seed and
dimension before this call.
Args:
struct_type (int): :class:`~cubiomes.StructureType` constant.
gen (Generator): Initialised generator.
block_x, block_z (int): Block coordinates (from :func:`get_structure_pos`).
flags (int): Optional structure-specific flags (e.g. biome variant
for villages).
Returns:
bool: ``True`` if the structure can generate there.
"""
return bool(cb.isViableStructurePos(struct_type, gen._g,
block_x, block_z, flags))
def is_viable_feature_biome(int mc, int struct_type, int biome_id) -> bool:
"""Check whether a biome can host a structure.
Args:
mc (int): MC version.
struct_type (int): :class:`~cubiomes.StructureType` constant.
biome_id (int): :class:`~cubiomes.BiomeID` value.
Returns:
bool
"""
return bool(cb.isViableFeatureBiome(mc, struct_type, biome_id))
def get_variant(int struct_type, int mc, uint64_t seed,
int block_x, int block_z, int biome_id=-1):
"""Retrieve variant information (rotation, size, flags) for a structure.
Not all structure types are supported; unsupported types return ``None``.
Args:
struct_type (int): :class:`~cubiomes.StructureType` constant.
mc (int): MC version.
seed (int): World seed.
block_x, block_z (int): Block-level position from :func:`get_structure_pos`.
biome_id (int): Biome at the position (use -1 if unknown).
Returns:
StructureVariant | None
"""
cdef StructureVariant sv = StructureVariant.__new__(StructureVariant)
if not cb.getVariant(&sv._sv, struct_type, mc, seed,
block_x, block_z, biome_id):
return None
return sv
def iter_strongholds(Generator gen, uint64_t seed48):
"""Return an iterator that yields stronghold positions in order.
Each value is an accurate ``(x, z)`` block coordinate pair obtained
after a biome check.
Args:
gen (Generator): Generator **already set up** with
:meth:`~Generator.apply_seed` for Overworld generation.
seed48 (int): World seed (lower 48 bits).
Returns:
StrongholdIterator
Example::
g = Generator(MCVersion.MC_1_21)
g.apply_seed(Dimension.DIM_OVERWORLD, 42)
for x, z in iter_strongholds(g, 42):
print(x, z)
"""
return StrongholdIterator(gen, seed48)
def init_first_stronghold(int mc, uint64_t seed48):
"""Return the approximate position of the first stronghold (no biome check).
This is faster than :func:`iter_strongholds` but accurate only to ±112
blocks.
Args:
mc (int): MC version.
seed48 (int): World seed (lower 48 bits).
Returns:
tuple[int, int]: Approximate ``(x, z)`` block coordinates.
"""
cdef cb.StrongholdIter sh
cdef cb.Pos pos = cb.initFirstStronghold(&sh, mc, seed48)
return (pos.x, pos.z)
def get_mineshafts(int mc, uint64_t seed,
int chunk_x, int chunk_z,
int chunk_w, int chunk_h,
int max_count=1024):
"""Find mineshaft positions within a chunk area.
Args:
mc (int): MC version.
seed (int): World seed.
chunk_x, chunk_z (int): Top-left corner of the area in chunks.
chunk_w, chunk_h (int): Width and height of the area in chunks.
max_count (int): Maximum number of results.
Returns:
list[tuple[int, int]]: Block ``(x, z)`` positions of mineshafts.
"""
cdef cb.Pos *out = <cb.Pos *>malloc(max_count * sizeof(cb.Pos))
if out is NULL:
raise MemoryError()
cdef int n = cb.getMineshafts(
mc, seed, chunk_x, chunk_z, chunk_w, chunk_h, out, max_count)
result = [(out[i].x, out[i].z) for i in range(n)]
free(out)
return result
def setup_biome_filter(int mc,
object required=None,
object excluded=None,
object match_any=None,
unsigned int flags=0) -> BiomeFilter:
"""Create a :class:`BiomeFilter` for use with
:meth:`Generator.check_for_biomes`.
Args:
mc (int): MC version.
required: Biome IDs that **all** must appear in the region.
excluded: Biome IDs that must **not** appear.
match_any: At least one biome from this list must appear.
flags (int): Filter flags — ``BF_APPROX = 0x01`` enables aggressive
(potentially lossy) pruning for speed.
Returns:
BiomeFilter
"""
return BiomeFilter(mc, required, excluded, match_any, flags)
def is_slime_chunk(uint64_t seed, int chunk_x, int chunk_z) -> bool:
"""Return True if the given chunk spawns slimes at any light level.
Args:
seed (int): World seed.
chunk_x, chunk_z (int): Chunk coordinates (block coords divided by 16).
Returns:
bool
"""
return bool(cb.isSlimeChunk(seed, chunk_x, chunk_z))
def get_shadow(uint64_t seed) -> int:
"""Compute the shadow seed for a given world seed.
The shadow seed produces mirrored structure positions.
Args:
seed (int): World seed.
Returns:
int: Shadow seed.
"""
return cb.getShadow(seed)
def move_structure(uint64_t base_seed, int reg_x, int reg_z) -> int:
"""Translate a base seed so that structures shift by ``(reg_x, reg_z)`` regions.
Useful for finding quad-witch-hut or quad-monument base seeds.
Args:
base_seed (int): Starting seed.
reg_x, reg_z (int): Region offset to apply.
Returns:
int: Translated seed (lower 48 bits).
"""
return cb.moveStructure(base_seed, reg_x, reg_z)
def chunk_generate_rnd(uint64_t world_seed,
int chunk_x, int chunk_z) -> int:
"""Compute the chunk-generation random seed used for caves/structures.
Args:
world_seed (int): World seed.
chunk_x, chunk_z (int): Chunk coordinates.
Returns:
int: 64-bit random seed.
"""
return cb.chunkGenerateRnd(world_seed, chunk_x, chunk_z)
def get_population_seed(int mc, uint64_t world_seed,
int x, int z) -> int:
"""Return the population seed for a given chunk (block) position.
Args:
mc (int): MC version.
world_seed (int): World seed.
x, z (int): Block coordinates (typically the chunk's origin block).
Returns:
int: 64-bit population seed.
"""
return cb.getPopulationSeed(mc, world_seed, x, z)
# ─── Biome property helpers ───────────────────────────────────────────────────
def biome_exists(int mc, int biome_id) -> bool:
"""Return True if the biome exists in the given MC version."""
return bool(cb.biomeExists(mc, biome_id))
def is_overworld_biome(int mc, int biome_id) -> bool:
"""Return True if the biome generates in the Overworld for this version."""
return bool(cb.isOverworld(mc, biome_id))
def get_dimension(int biome_id) -> int:
"""Return the dimension a biome belongs to (0=Overworld, -1=Nether, +1=End)."""
return cb.getDimension(biome_id)
def get_mutated(int mc, int biome_id) -> int:
"""Return the mutated/hills variant of a biome, or -1 if none exists."""
return cb.getMutated(mc, biome_id)
def get_category(int mc, int biome_id) -> int:
"""Return the temperature/climate category of a biome."""
return cb.getCategory(mc, biome_id)
def are_similar(int mc, int biome_id1, int biome_id2) -> bool:
"""Return True if two biomes share a climate category."""
return bool(cb.areSimilar(mc, biome_id1, biome_id2))
def is_mesa(int biome_id) -> bool:
"""Return True if the biome is a badlands (mesa) variant."""
return bool(cb.isMesa(biome_id))
def is_shallow_ocean(int biome_id) -> bool:
"""Return True if the biome is a shallow ocean."""
return bool(cb.isShallowOcean(biome_id))
def is_deep_ocean(int biome_id) -> bool:
"""Return True if the biome is a deep ocean."""
return bool(cb.isDeepOcean(biome_id))
def is_oceanic(int biome_id) -> bool:
"""Return True if the biome is any ocean type (shallow or deep)."""
return bool(cb.isOceanic(biome_id))
def is_snowy(int biome_id) -> bool:
"""Return True if the biome is snowy."""
return bool(cb.isSnowy(biome_id))

228
cubiomes/enums.py Normal file
View file

@ -0,0 +1,228 @@
"""Integer enumerations mirroring the cubiomes C enums.
All values are directly usable wherever the C API expects ``int`` constants.
"""
from enum import IntEnum
class MCVersion(IntEnum):
"""Minecraft version constants.
``MC_NEWEST`` always points to the latest supported version.
Aliases like ``MC_1_21`` refer to the latest patch of that major release.
"""
MC_UNDEF = 0
MC_B1_7 = 1
MC_B1_8 = 2
MC_1_0_0 = 3; MC_1_0 = 3
MC_1_1_0 = 4; MC_1_1 = 4
MC_1_2_5 = 5; MC_1_2 = 5
MC_1_3_2 = 6; MC_1_3 = 6
MC_1_4_7 = 7; MC_1_4 = 7
MC_1_5_2 = 8; MC_1_5 = 8
MC_1_6_4 = 9; MC_1_6 = 9
MC_1_7_10 = 10; MC_1_7 = 10
MC_1_8_9 = 11; MC_1_8 = 11
MC_1_9_4 = 12; MC_1_9 = 12
MC_1_10_2 = 13; MC_1_10 = 13
MC_1_11_2 = 14; MC_1_11 = 14
MC_1_12_2 = 15; MC_1_12 = 15
MC_1_13_2 = 16; MC_1_13 = 16
MC_1_14_4 = 17; MC_1_14 = 17
MC_1_15_2 = 18; MC_1_15 = 18
MC_1_16_1 = 19
MC_1_16_5 = 20; MC_1_16 = 20
MC_1_17_1 = 21; MC_1_17 = 21
MC_1_18_2 = 22; MC_1_18 = 22
MC_1_19_2 = 23
MC_1_19_4 = 24; MC_1_19 = 24
MC_1_20_6 = 25; MC_1_20 = 25
MC_1_21_1 = 26
MC_1_21_3 = 27
MC_1_21_4 = 28; MC_1_21_WD = 28
MC_1_21_5 = 29
MC_1_21_6 = 30
MC_1_21_9 = 31
MC_1_21_11 = 32; MC_1_21 = 32
MC_26_1 = 33
MC_26_2 = 34
MC_26_3 = 35; MC_NEWEST = 35
class Dimension(IntEnum):
"""Dimension identifiers."""
DIM_NETHER = -1
DIM_OVERWORLD = 0
DIM_END = 1
DIM_UNDEF = 1000
class BiomeID(IntEnum):
"""All biome IDs across all supported MC versions.
Modern names (e.g. ``windswept_hills``) and legacy aliases
(e.g. ``extremeHills``) are both provided.
"""
NONE = -1
# ── Base biomes ──────────────────────────────────────────────────────────
ocean = 0
plains = 1
desert = 2
mountains = 3; extremeHills = 3
forest = 4
taiga = 5
swamp = 6; swampland = 6
river = 7
nether_wastes = 8; hell = 8
the_end = 9; sky = 9
frozen_ocean = 10; frozenOcean = 10
frozen_river = 11; frozenRiver = 11
snowy_tundra = 12; icePlains = 12
snowy_mountains = 13; iceMountains = 13
mushroom_fields = 14; mushroomIsland = 14
mushroom_field_shore = 15; mushroomIslandShore = 15
beach = 16
desert_hills = 17; desertHills = 17
wooded_hills = 18; forestHills = 18
taiga_hills = 19; taigaHills = 19
mountain_edge = 20; extremeHillsEdge = 20
jungle = 21
jungle_hills = 22; jungleHills = 22
jungle_edge = 23; jungleEdge = 23
deep_ocean = 24; deepOcean = 24
stone_shore = 25; stoneBeach = 25
snowy_beach = 26; coldBeach = 26
birch_forest = 27; birchForest = 27
birch_forest_hills = 28; birchForestHills = 28
dark_forest = 29; roofedForest = 29
snowy_taiga = 30; coldTaiga = 30
snowy_taiga_hills = 31; coldTaigaHills = 31
giant_tree_taiga = 32; megaTaiga = 32
giant_tree_taiga_hills = 33; megaTaigaHills = 33
wooded_mountains = 34; extremeHillsPlus = 34
savanna = 35
savanna_plateau = 36; savannaPlateau = 36
badlands = 37; mesa = 37
wooded_badlands_plateau = 38; mesaPlateau_F = 38
badlands_plateau = 39; mesaPlateau = 39
small_end_islands = 40
end_midlands = 41
end_highlands = 42
end_barrens = 43
warm_ocean = 44; warmOcean = 44
lukewarm_ocean = 45; lukewarmOcean = 45
cold_ocean = 46; coldOcean = 46
deep_warm_ocean = 47; warmDeepOcean = 47
deep_lukewarm_ocean = 48; lukewarmDeepOcean = 48
deep_cold_ocean = 49; coldDeepOcean = 49
deep_frozen_ocean = 50; frozenDeepOcean = 50
# ── Beta biomes ──────────────────────────────────────────────────────────
seasonal_forest = 51
rainforest = 52
shrubland = 53
the_void = 127
# ── Mutated variants ─────────────────────────────────────────────────────
sunflower_plains = 129
desert_lakes = 130
gravelly_mountains = 131
flower_forest = 132
taiga_mountains = 133
swamp_hills = 134
ice_spikes = 140
modified_jungle = 149
modified_jungle_edge = 151
tall_birch_forest = 155
tall_birch_hills = 156
dark_forest_hills = 157
snowy_taiga_mountains = 158
giant_spruce_taiga = 160
giant_spruce_taiga_hills = 161
modified_gravelly_mountains = 162
shattered_savanna = 163
shattered_savanna_plateau = 164
eroded_badlands = 165
modified_wooded_badlands_plateau = 166
modified_badlands_plateau = 167
# ── 1.14 ─────────────────────────────────────────────────────────────────
bamboo_jungle = 168
bamboo_jungle_hills = 169
# ── 1.16 Nether ──────────────────────────────────────────────────────────
soul_sand_valley = 170
crimson_forest = 171
warped_forest = 172
basalt_deltas = 173
# ── 1.17 caves ───────────────────────────────────────────────────────────
dripstone_caves = 174
lush_caves = 175
# ── 1.18 ─────────────────────────────────────────────────────────────────
meadow = 177
grove = 178
snowy_slopes = 179
jagged_peaks = 180
frozen_peaks = 181
stony_peaks = 182
# ── 1.19 ─────────────────────────────────────────────────────────────────
deep_dark = 183
mangrove_swamp = 184
# ── 1.20 ─────────────────────────────────────────────────────────────────
cherry_grove = 185
# ── 1.21 Winter Drop ─────────────────────────────────────────────────────
pale_garden = 186
# ── 26.x ─────────────────────────────────────────────────────────────────
sulfur_caves = 187
dappled_forest = 188
class StructureType(IntEnum):
"""Structure type constants passed to structure-finding functions."""
Feature = 0 # temple generation attempts pre-1.13
Desert_Pyramid = 1
Jungle_Temple = 2; Jungle_Pyramid = 2
Swamp_Hut = 3
Igloo = 4
Village = 5
Ocean_Ruin = 6
Shipwreck = 7
Monument = 8
Mansion = 9
Outpost = 10
Ruined_Portal = 11
Ruined_Portal_N = 12
Ancient_City = 13
Treasure = 14
Mineshaft = 15
Desert_Well = 16
Geode = 17
Fortress = 18
Bastion = 19
Nether_Fossil = 20
End_City = 21
End_Gateway = 22
End_Island = 23
Trail_Ruins = 24
Trial_Chambers = 25
Abandoned_Camp = 26
Stronghold = 27
# Generator flags
LARGE_BIOMES = 0x1
NO_BETA_OCEAN = 0x2
FORCE_OCEAN_VARIANTS = 0x4
# BiomeFilter flags
BF_APPROX = 0x01
BF_FORCED_OCEAN = FORCE_OCEAN_VARIANTS

1418
cubiomes/search.py Normal file

File diff suppressed because it is too large Load diff