cubiomes 0.3.3

A safe rust wrapper for the cubiome library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Minecraft biome data generator
//!
//! This module is used to generate biomes from minecraft seeds
//! using the [Generator]
//!
//! # Usage
//!
//! For simple usage getting a biome at a specific place see
//! [`Generator::get_biome_at()`]
//!
//! For more complicated usage, use a [`Cache`] generated with [`Cache::new()`]
//! And for generating images, see [`Cache::to_image()`].
//!
//! For structure generation, see [`crate::structures`]
//!
//! ## Optimal height
//!
//! For the y value in generation you should generally use minecraft build limit
//! for surface biomes in the overworld. (either 320 for post 1.18, or 255 for
//! pre 1.18) Note that this isn't exhaustive, please check the
//! [minecraft wiki](https://minecraft.wiki/w/Altitude#History) for an
//! exhaustive list of changes in worldheight.
//!
//! # Details
//!
//! This module follow closely to how the underlying cubiomes library works, but
//! the features have been wrapped by a safe rust api

pub use position::*;
pub use range::*;

use crate::{enums, noise::BiomeNoise};
use bitflags::bitflags;
use cubiomes_sys::{
    enums::{Dimension, MCVersion},
    getMinCacheSize, mapApproxHeight,
    num_traits::FromPrimitive,
};
use error::GeneratorError;
use std::{
    alloc::{alloc, dealloc, Layout},
    fmt::Debug,
    mem::transmute,
};

pub mod error;
mod position;
mod range;

#[cfg(test)]
mod tests;

bitflags! {
    /// Flags for the cubiomes generator
    ///
    /// # Usage
    /// This indicates flags to pass to cubiomes. Unless you know what
    /// you are doing, you should probably leave these empty. Check the
    /// actual cubiomes library for documentation on what they do.
    pub struct GeneratorFlags: u32 {
        #[allow(missing_docs)]
        const LargeBiomes = 0x1;
        #[allow(missing_docs)]
        const NoBetaOcean = 0x2;
        #[allow(missing_docs)]
        const ForceOceanVariants = 0x4;
        //the source may set any bits
        #[allow(missing_docs)]
        const _ = !0;
    }
}

/// The cubiomes generator
///
/// This is the struct which holds a cubiomes generator
/// and is used for most actions with the generator
///
/// A new instance of the generator can be created with [`Generator::new()`]
///
/// Biomes can be generated either with [`Self::get_biome_at()`] for single
/// points, or in conjuntion with a [`Cache`] generated by [`Cache::new()`]
#[derive(Debug)]
pub struct Generator {
    generator: *mut cubiomes_sys::Generator,
}

impl Drop for Generator {
    fn drop(&mut self) {
        // Safety:
        // The memory is safe to deallocate as its been allocated in new
        // and the pointer to it is dropped, so it is never referred to again
        unsafe {
            dealloc(self.generator as *mut u8, Layout::new::<Generator>());
        }
    }
}

// SAFETY: As the raw pointer inside generator is exclusive to this instance of
// generator, sending it in between threads should be safe. Only way to access
// the raw pointer is via unsafe.
unsafe impl Send for Generator {}

// SAFETY: The generator shouldn't have interior mutation without an exclusive
// mutable reference. All public api:s which mutate the internal generator
// (even briefly) should require an exclusive reference.
unsafe impl Sync for Generator {}

impl Generator {
    /// Initializes a new generator for the given minecraft version and flags
    /// with a seed and dimension applied
    ///
    /// This function initializes a new cubiomes generator and then gives
    /// it a seed.
    ///
    /// # Examples
    ///
    /// ```
    /// use cubiomes::generator::{Generator, GeneratorFlags};
    /// use cubiomes::enums::{MCVersion, Dimension};
    ///
    /// let seed: i64 = -4804349813814383506;
    /// let mc_version = MCVersion::MC_1_21_WD;
    ///
    /// let generator = Generator::new(mc_version, seed, Dimension::DIM_OVERWORLD, GeneratorFlags::empty());
    ///
    /// // Use the generator for something
    /// ```
    #[must_use]
    pub fn new(
        mc_version: MCVersion,
        seed: i64,
        dimension: enums::Dimension,
        flags: GeneratorFlags,
    ) -> Self {
        // SAFETY:
        // the generator is immediatly given a seed
        unsafe {
            let mut generator = Generator::new_without_seed(mc_version, flags);
            generator.apply_seed(dimension, seed);

            generator
        }
    }

    /// Initializes a new generator for the given minecraft version and flags
    ///
    /// This function initializes a new cubiomes generator for the specified
    /// version of minecraft with the specified flags. To use the generator it
    /// must be given a seed with [`Self::apply_seed()`]
    ///
    /// # Safety
    /// Before using any generation functions one must use
    /// [`Self::apply_seed()`] to give the generator a seed, otherwise the
    /// generation will fail.
    ///
    /// # Examples
    /// ```
    ///    
    /// use cubiomes::generator::Generator;
    /// use cubiomes::enums::MCVersion;
    /// use cubiomes::generator::GeneratorFlags;
    ///
    /// // Version of minecraft to use with the generator
    /// let mc_version = MCVersion::MC_1_21_WD;
    /// let generator;
    /// unsafe{
    ///     generator = Generator::new_without_seed(mc_version, GeneratorFlags::empty());
    /// }
    /// ```
    #[must_use]
    pub unsafe fn new_without_seed(version: MCVersion, flags: GeneratorFlags) -> Self {
        // SAFETY:
        // The function is safe since the generated pointer
        // points to memory that can fit a Generator and
        // the pointer is stored as a pointer
        unsafe {
            let generator =
                alloc(Layout::new::<cubiomes_sys::Generator>()) as *mut cubiomes_sys::Generator;

            cubiomes_sys::setupGenerator(generator, version as i32, flags.bits());
            Self { generator }
        }
    }

    /// Sets the seed for the generator
    ///
    /// Sets a new seed to the generator. This can either be used for
    /// initialization if the generator was generated with
    /// [`Self::new_without_seed()`] or changing the seed of the generator
    pub fn apply_seed(&mut self, dimension: enums::Dimension, seed: i64) {
        // SAFETY:
        // As the generator is correctly initialized and its fields are private
        // the applySeed function is only given valid instances of generator
        unsafe {
            cubiomes_sys::applySeed(
                self.generator,
                dimension as i32,
                transmute::<i64, u64>(seed),
            );
        }
    }

    /// Tries to get a biomeid at the specific location.
    pub fn get_biome_at(&self, x: i32, y: i32, z: i32) -> Result<enums::BiomeID, GeneratorError> {
        // SAFETY:
        // As the generator is correctly initialized and its fields are private
        // the applySeed function is only given valid instances of generator.
        //
        // The scale enum guarantees that getBiomeAt is only given a scale of 1 or 4
        // As specified in its documentation
        unsafe {
            match cubiomes_sys::getBiomeAt(self.generator, Scale::Block as i32, x, y, z) {
                -1 => Err(GeneratorError::GetBiomeAtFailure),
                n => FromPrimitive::from_i32(n).ok_or(GeneratorError::BiomeIDOutOfRange(n)),
            }
        }
    }

    /// Gets the seed of [self]
    #[must_use]
    pub fn seed(&self) -> i64 {
        // SAFETY:
        // The generator pointer can't be null as its been initialized
        // when constructing this struct
        unsafe { transmute::<u64, i64>((*self.generator).seed) }
    }

    /// Gets the current dimension of the generator
    ///
    /// # Panics
    /// Panics if generator has an invalid dimension
    pub fn dimension(&self) -> enums::Dimension {
        // SAFETY: self has been initialized so ptr shouldn't be null
        unsafe { Dimension::from_i32((*self.as_ptr()).dim).expect("dimension not valid") }
    }

    /// Gets the minecraft version of [self]
    ///
    /// # Panics
    /// Panics if the generator has an invalid MCVersion
    #[must_use]
    pub fn minecraft_version(&self) -> MCVersion {
        // SAFETY:
        // The generator pointer can't be null as its been initialized
        // when constructing this struct
        MCVersion::from_i32(unsafe { *self.generator }.mc)
            .expect("Cubiomes generator has an invalid mc version")
    }

    /// Generates a vector containing approximate surface height within the
    /// area.
    ///
    /// The surface noise is generated at [Scale::Quad], eg. locations map 1:4.
    ///
    /// The vector contains the approximate height of each position and is
    /// indexed as follows: `[buf_z * size_z + x]`. With buf_z being relative to
    /// the top left position of the buffer.
    ///
    /// If noise is initialized for wrong version or dimension results may not
    /// makes sense.
    ///
    /// # Panics
    /// If attempting to generate surface noise for beta minecraft.
    ///
    /// Also panics if given an incorrect noicevariant.
    pub fn approx_surface_noise(
        &self,
        x: i32,
        z: i32,
        size_x: u32,
        size_z: u32,
        surface_noise: &BiomeNoise,
    ) -> Option<Vec<f32>> {
        if self.minecraft_version() == MCVersion::MC_B1_7
            || self.minecraft_version() == MCVersion::MC_B1_8
        {
            panic!("Surface height approximation not currently supported for beta minecraft")
        } else {
            let capacity = (size_x * size_z) as usize;

            let mut buff = Vec::with_capacity(capacity);

            let BiomeNoise::Release(surface_noise) = surface_noise else {
                panic!("Tried to use beta noise with non beta generator")
            };

            // SAFETY: Foreign function is called with correct arguments
            //
            // buff can hold enough items to be filled
            // ids can be null according to docs
            // surface noise is initialized
            let res = unsafe {
                mapApproxHeight(
                    buff.as_mut_ptr(),
                    std::ptr::null_mut(),
                    self.as_ptr(),
                    surface_noise.as_ptr(),
                    x,
                    z,
                    size_x as i32,
                    size_z as i32,
                )
            };

            if res != 0 {
                return None;
            }

            // SAFETY: as buff was filled with ffi it should hold capacity elements
            unsafe {
                buff.set_len(capacity);
            }

            Some(buff)
        }
    }

    /// Gets a raw mutable pointer to the underlying generator
    ///
    /// This can be used for calling into functions from `cubiomes_sys` with
    /// the raw pointer, or other activities invloving the raw cubiomes
    /// generator
    ///
    /// # Safety
    /// The pointer must remain pointing to a valid instance of the cubiomes
    /// generator
    ///
    /// The pointer shouldn't outlive the generator, as when dropped it gets
    /// unallocated
    ///
    /// Also keep in mind thread safety, if working in a multithreaded
    /// environment.
    pub unsafe fn as_mut_ptr(&mut self) -> *mut cubiomes_sys::Generator {
        self.generator
    }

    /// Gets a raw const pointer to the underlying generator
    ///
    /// This can be used for calling into `cubiomes_sys` with the raw pointer
    /// or other such things
    ///
    /// # Safety
    /// The data the pointer points to, should not be mutated. Use
    /// [`Self::as_mut_ptr()`] for mutating data.
    ///
    /// The pointer shouldn't outlive the generator, as when the generator is
    /// dropped the memory it points to becomes unallocated
    ///
    /// Also keep in mind thread safety. Do not mutate the type if you do not
    /// have exclusive access.
    #[must_use]
    pub unsafe fn as_ptr(&self) -> *const cubiomes_sys::Generator {
        self.generator
    }

    fn min_cache_size_from_range(&self, range: Range) -> usize {
        #[allow(clippy::unwrap_used)]
        let raw_range: cubiomes_sys::Range = range.try_into().unwrap();

        // SAFETY:
        // The conversion from cubiomes_sys::Range provides a range that fits the
        // requirements of the function
        unsafe {
            self.unchecked_min_cache_size(raw_range.scale, raw_range.sx, raw_range.sy, raw_range.sz)
        }
    }

    /// Gets the minimum cache size for a specific sized range
    ///
    /// y can be either 0 or 1 for a plane
    ///
    /// # Panics
    /// Panics if scale, `size_x`, or `size_z` are 0 or less and if `size_y` is
    /// less than 0
    unsafe fn unchecked_min_cache_size(
        &self,
        scale: i32,
        size_x: i32,
        size_y: i32,
        size_z: i32,
    ) -> usize {
        // SAFETY:
        // The unsafety is documented for the function.
        //
        // The requirement for this is checked from the source code and not from
        // documentation
        unsafe { getMinCacheSize(self.generator, scale, size_x, size_y, size_z) }
    }

    /// Fills the provided cache from the generator
    ///
    /// # Safety
    /// The caller must guarantee, that the cache is able to contain the
    /// generated data. The best way to guarantee this, is to use a cache
    /// generated from this generator
    unsafe fn unchecked_generate_biomes_to_cache(
        &self,
        cache: &mut Cache,
    ) -> Result<(), GeneratorError> {
        let result_num = cubiomes_sys::genBiomes(
            self.generator,
            cache.buffer.as_mut_ptr(),
            cache.range.try_into()?,
        );

        // If error is returned from genbiomes, dont resize the vec as it may contain
        // garbage data
        if result_num != 0 {
            return Err(GeneratorError::GenBiomeToCacheFailure(result_num));
        }

        // We set the caches lenght to what an user would want to read from it as we
        // can't be sure if cubiomes has actually initialized all variables beyond
        // the readable area.
        cache
            .buffer
            .set_len(cache.calculate_readable_cache_length());

        Ok(())
    }

    #[allow(unused)]
    unsafe fn seed_for_cubiomes(&self) -> u64 {
        // SAFETY: Transmute between same sized primitives is safe
        unsafe { transmute::<i64, u64>(self.seed()) }
    }

    /// Generates a heightmap for the supplied area between bottom and top
    ///
    /// This function generates a heightmap for the supplied area. Position is
    /// given in [`Scale::Quad`], eg 1:4 scale.
    ///
    /// Black corresponds to `height <= bottom` and White `height >= top`. The
    /// colors are mapped linearly in between the supplied values.
    ///
    /// Returns none if generator cannot generate a heightmap. For example if
    /// trying to generate nether heights or end before end existed.
    ///
    /// # Examples
    /// ```
    #[doc = include_str!("../../examples/generate_heightmap.rs")]
    /// ```
    #[cfg(feature = "image")]
    #[allow(clippy::too_many_arguments)]
    pub fn generate_heightmap_image(
        &self,
        x: i32,
        z: i32,
        size_x: u32,
        size_z: u32,
        bottom: f32,
        top: f32,
        surface_noise: &BiomeNoise,
    ) -> Option<image::GrayImage> {
        use image::GrayImage;

        let buf = self.approx_surface_noise(x, z, size_x, size_z, surface_noise)?;

        Some(GrayImage::from_fn(size_x, size_z, |img_x, img_z| {
            [float_between(
                buf[(img_z * size_z + img_x) as usize],
                bottom,
                top,
            )]
            .into()
        }))
    }
}

fn float_between(n: f32, bottom: f32, top: f32) -> u8 {
    let range = top - bottom;

    ((n - bottom) * ((u8::MAX as f32) / range)).clamp(u8::MIN as f32, u8::MAX as f32) as u8
}

/// A cache for generating and holding a chunk of biome data
///
/// The cache is usually generated with [`Self::new()`] and holds a vector
/// filled with biome data. The biome data is automatically updated whenever the
/// cache is created or moved.
///
/// The cache should be thought of as a view into the generator which it was
/// created with.
#[derive(Clone)]
pub struct Cache<'generator> {
    buffer: Vec<i32>,
    range: Range,
    generator: &'generator Generator,
}

//Custom dbg implementation, so we get the cache formatted as a table
impl Debug for Cache<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, ":")?;
        writeln!(f, "Range: {:?}", &self.range)?;
        writeln!(f, "Cache: ")?;

        for line in self.buffer.chunks(self.range.size_x as usize) {
            writeln!(f, "{line:?}")?;
        }
        Ok(())
    }
}

impl Cache<'_> {
    /// Generates a new cache for the given generator
    ///
    /// This function creates a new [`Cache`] against this version of the
    /// generator, and fills it.
    pub fn new(generator: &Generator, range: Range) -> Result<Cache<'_>, GeneratorError> {
        let cache_size = generator.min_cache_size_from_range(range);
        let cache = Vec::with_capacity(cache_size);

        let mut cache = Cache {
            buffer: cache,
            range,
            generator,
        };

        cache.fill_cache().and(Ok(cache))
    }

    /// Fills the cache so it can be read
    fn fill_cache(&mut self) -> Result<(), GeneratorError> {
        // Safety:
        // As the cache holds a reference to the generator, the generator
        // could not have been modified after the vec was allocated so the
        // vec inside this cache holds enough space for the generator
        unsafe { self.generator.unchecked_generate_biomes_to_cache(self) }
    }

    /// Gets a reference to the internal representation of the cache.
    ///
    /// The cache is a linear array which can be accessed at the following
    /// index: ``y * self.range.sx * self.range.sz + z * self.range.sx + x``
    /// If the cache is a plane use y=0 for the index
    ///
    /// # Examples
    ///
    /// ```
    /// use cubiomes::generator::{Cache, Range, Scale};
    ///
    /// use cubiomes::generator::{Generator, GeneratorFlags};
    /// use cubiomes::enums::{MCVersion, Dimension, BiomeID};
    ///
    /// let mut generator = Generator::new(
    ///     MCVersion::MC_1_21_WD,
    ///     -380434930381432806,
    ///     Dimension::DIM_OVERWORLD,
    ///     GeneratorFlags::empty()
    /// );
    ///
    /// let mut cache = Cache::new(&generator, Range {
    ///     scale: Scale::Block,
    ///     x: 512,
    ///     z: -512,
    ///     size_x: 64,
    ///     size_z: 64,
    ///     y: 100,
    ///     size_y: 0,
    /// }).expect("failed to fill cache");
    ///
    /// // Read the cache at z=32, x=5
    ///
    /// assert_eq!(cache.as_vec()[(13 + cache.range().size_x + 5) as usize], BiomeID::plains as i32);
    #[inline]
    #[must_use]
    pub fn as_vec(&self) -> &Vec<i32> {
        &self.buffer
    }

    /// Gets a reference to the range used by this cache
    ///
    /// Gets the range this cache was generated with. Useful for
    /// if you want to read from the caches.
    ///
    /// See example from [`Self::as_vec()`] for example usage
    #[inline]
    #[must_use]
    pub fn range(&self) -> &Range {
        &self.range
    }

    /// This function gets a biome at the specified point in the cache
    ///
    /// The specified point is relative to the left upper corner of
    /// the caches range.
    ///
    /// The cache start from x:0 y:0 mapping to the 0,0 of the range it
    /// was generated with. This means that attempting to read x: 16 or y:16
    /// on a cache with a size of 16 will be out of bounds.
    pub fn biome_at(&self, x: u32, y: u32, z: u32) -> Result<enums::BiomeID, GeneratorError> {
        let raw_biomeid = *self
            .buffer
            .get((y * self.range.size_x * self.range.size_z + z * self.range.size_x + x) as usize)
            .ok_or(GeneratorError::IndexOutOfBounds)?;

        enums::BiomeID::from_i32(raw_biomeid).ok_or(GeneratorError::BiomeIDOutOfRange(raw_biomeid))
    }

    /// Moves the cache to the new position without a reallocation and fills it.
    ///
    /// This function can be used to generate multiple areas in sequence,
    /// without needing to reallocate memory, saving performance.
    pub fn move_cache(&mut self, x: i32, y: i32, z: i32) -> Result<(), GeneratorError> {
        let new_range = Range {
            x,
            z,
            y,
            ..self.range
        };

        // As the size of the cache is only affeted by scale and size, moving the
        // location won't change the excpected cache size

        self.range = new_range;

        // Refills the cache with the new spot
        self.fill_cache()
    }

    /// Generates an `image::ImageBuffer` from this cache.
    ///
    /// This function requires crate feature image
    ///
    /// The imagebuffer is generated with the given
    /// [`crate::colors::BiomeColorMap`]. The image is an rgb image.
    ///
    /// If you want to do further processing of the image. You'll probably need
    /// to depend on the image crate in your project, as we dont re-export the
    /// image crate.
    ///
    /// # Panics
    /// Panics if the cache has not been filled.
    ///
    /// # Examples
    /// ```
    #[doc = include_str!("../../examples/generate_image.rs")]
    /// ```
    #[cfg(feature = "image")]
    pub fn to_image(&self, color_map: crate::colors::BiomeColorMap) -> image::RgbImage {
        use image::RgbImage;

        RgbImage::from_fn(self.range.size_x, self.range.size_z, |x, z| {
            color_map[self
                .biome_at(x, 0, z)
                .expect("Failed to get biome within cache (cache is probably unitialized)")]
            .into()
        })
    }

    /// Calculates the actual size of readable data within the cache
    fn calculate_readable_cache_length(&self) -> usize {
        let y_size = match self.range.size_y {
            0 => 1,
            n => n,
        };
        (self.range.size_x * self.range.size_z * y_size) as usize
    }
}