# 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, int64_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 = 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, long long 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 |= (1) << b elif 128 <= b < 192: valid_m |= (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 = malloc(max_results * sizeof(cb.Pos)) cdef int *siz_buf = 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, long long 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 = malloc(req_len * sizeof(int)) for i, v in enumerate(required): req_arr[i] = int(v) if excluded: exc_len = len(excluded) exc_arr = 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 = 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, long long 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, long long 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, long long 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, long long 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, long long 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, long long 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 = 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(long long 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(long long 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(long long 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(long long 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, long long 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))