### Minimal Working Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md A minimal example demonstrating the core functionality of the library. ```rust use block_mesh_rs::meshing_algorithms::greedy_quads; use block_mesh_rs::buffers::GreedyQuadsBuffer; let voxels = vec![...]; // Simplified voxel data let mut buffer = GreedyQuadsBuffer::new(); greedy_quads(&voxels, &mut buffer); let mesh_data = buffer.into_mesh_data(); println!("Generated mesh data: {:?}", mesh_data); ``` -------------------------------- ### Compile and Run Render Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/examples-crate/README.md Navigates to the examples-crate directory and compiles/runs the 'render' example using Cargo. ```bash cd examples-crate cargo run --example render ``` -------------------------------- ### MaxMerge Strategy Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Example of implementing a custom `MergeStrategy` that attempts to merge quads as much as possible. ```rust use block_mesh_rs::merge_strategy::{MergeStrategy, FaceStrides}; struct MaxMerge; impl MergeStrategy for MaxMerge { fn should_merge(&self, _strides: &FaceStrides, _a: usize, _b: usize) -> bool { true // Always return true to maximize merging } } // Usage: Pass an instance of MaxMerge to greedy_quads_with_merge_strategy ``` -------------------------------- ### NoMerge Strategy Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Example of implementing a custom `MergeStrategy` that performs no merging (1x1 quads only). ```rust use block_mesh_rs::merge_strategy::{MergeStrategy, FaceStrides}; struct NoMerge; impl MergeStrategy for NoMerge { fn should_merge(&self, _strides: &FaceStrides, _a: usize, _b: usize) -> bool { false // Always return false to prevent merging } } // Usage: Pass an instance of NoMerge to greedy_quads_with_merge_strategy ``` -------------------------------- ### Complete Block Meshing Usage Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md A comprehensive example demonstrating the use of GreedyQuadsBuffer for generating quads via the greedy meshing algorithm and UnitQuadBuffer with visible_block_faces for identifying visible faces. It includes custom Voxel implementation and buffer processing. ```rust use block_mesh::{ greedy_quads, visible_block_faces, GreedyQuadsBuffer, UnitQuadBuffer, MergeVoxel, Voxel, VoxelVisibility, OrientedBlockFace, UnorientedQuad }; use ndshape::{ConstShape, ConstShape3u32}; #[derive(Clone, Copy, Eq, PartialEq)] struct Voxel(u32); impl Voxel { fn get_visibility(&self) -> VoxelVisibility { if self.0 != 0 { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } impl MergeVoxel for Voxel { type MergeValue = u32; type MergeValueFacingNeighbour = u32; fn merge_value(&self) -> u32 { self.0 } fn merge_value_facing_neighbour(&self) -> u32 { self.0 } } type ChunkShape = ConstShape3u32<18, 18, 18>; let voxels = vec![Voxel(1); ChunkShape::SIZE as usize]; // Using GreedyQuadsBuffer let mut greedy_buffer = GreedyQuadsBuffer::new(voxels.len()); greedy_quads( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut greedy_buffer, ); println!("Greedy quads: {}", greedy_buffer.quads.num_quads()); // Process results by face for (face_idx, quads) in greedy_buffer.quads.groups.iter().enumerate() { for quad in quads { let face = &RIGHT_HANDED_Y_UP_CONFIG.faces[face_idx]; // Get vertex positions let positions = face.quad_mesh_positions(quad, 1.0); let normals = face.quad_mesh_normals(); let indices = face.quad_mesh_indices(0); println!("Face {}: quad at {:?}", face_idx, quad.minimum); } } // Reuse buffer for next chunk greedy_buffer.reset(voxels.len()); greedy_quads( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut greedy_buffer, ); // Using UnitQuadBuffer with visible_block_faces let mut unit_buffer = UnitQuadBuffer::new(); visible_block_faces( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut unit_buffer, ); println!("Visible faces: {}", unit_buffer.num_quads()); ``` -------------------------------- ### HorizontalMerge Strategy Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Example of implementing a custom `MergeStrategy` for horizontal strip merging. ```rust use block_mesh_rs::merge_strategy::{MergeStrategy, FaceStrides}; struct HorizontalMerge; impl MergeStrategy for HorizontalMerge { fn should_merge(&self, strides: &FaceStrides, _a: usize, _b: usize) -> bool { // Logic to determine if quads can be merged horizontally // This would involve checking adjacency and material/color consistency along the horizontal axis. true // Placeholder: Implement actual horizontal merging logic } } // Usage: Pass an instance of HorizontalMerge to greedy_quads_with_merge_strategy ``` -------------------------------- ### Greedy Quads Meshing Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/meshing-algorithms.md An example demonstrating the usage of the greedy_quads function with custom voxel types and shape configurations. It shows how to initialize voxels, call the meshing algorithm, and print the number of generated quads. ```rust use block_mesh::{ greedy_quads, GreedyQuadsBuffer, MergeVoxel, Voxel, VoxelVisibility, RIGHT_HANDED_Y_UP_CONFIG }; use ndshape::{ConstShape, ConstShape3u32}; #[derive(Clone, Copy, Eq, PartialEq)] struct MaterialVoxel { material: u32, } impl Voxel for MaterialVoxel { fn get_visibility(&self) -> VoxelVisibility { if self.material != 0 { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } impl MergeVoxel for MaterialVoxel { type MergeValue = u32; type MergeValueFacingNeighbour = u32; fn merge_value(&self) -> Self::MergeValue { self.material } fn merge_value_facing_neighbour(&self) -> Self::MergeValueFacingNeighbour { self.material } } type ChunkShape = ConstShape3u32<18, 18, 18>; let voxels = vec![ MaterialVoxel { material: 1 }; ChunkShape::SIZE as usize ]; let mut buffer = GreedyQuadsBuffer::new(voxels.len()); greedy_quads( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer, ); println!("Generated {} quads", buffer.quads.num_quads()); ``` -------------------------------- ### Handling Multiple Materials Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Example of how to manage and generate meshes for voxels with different materials. ```rust use block_mesh_rs::meshing_algorithms::greedy_quads; use block_mesh_rs::buffers::GreedyQuadsBuffer; // Assume voxels store material information let voxels = vec![...]; let mut buffer = GreedyQuadsBuffer::new(); greedy_quads(&voxels, &mut buffer); // The buffer will contain quads categorized by material if voxels are structured accordingly. ``` -------------------------------- ### Minimal Greedy Quads Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/quick-reference.md This example demonstrates the basic usage of the greedy_quads algorithm to generate a mesh from a volume of voxels. It defines a simple Voxel type and uses GreedyQuadsBuffer to store the resulting quads. ```rust use block_mesh::{ greedy_quads, GreedyQuadsBuffer, MergeVoxel, Voxel, VoxelVisibility, RIGHT_HANDED_Y_UP_CONFIG }; use ndshape::{ConstShape, ConstShape3u32}; #[derive(Clone, Copy, Eq, PartialEq)] struct Voxel(bool); impl Voxel { fn get_visibility(&self) -> VoxelVisibility { if self.0 { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } impl MergeVoxel for Voxel { type MergeValue = bool; type MergeValueFacingNeighbour = bool; fn merge_value(&self) -> bool { self.0 } fn merge_value_facing_neighbour(&self) -> bool { self.0 } } type Shape = ConstShape3u32<18, 18, 18>; let voxels = vec![Voxel(true); Shape::SIZE as usize]; let mut buffer = GreedyQuadsBuffer::new(voxels.len()); greedy_quads( &voxels, &Shape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer ); println!("Quads: {}", buffer.quads.num_quads()); ``` -------------------------------- ### Fetch Git LFS Assets Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/examples-crate/README.md Installs and fetches assets tracked by Git LFS. Ensure Git LFS is installed before running. ```bash git lfs fetch ``` -------------------------------- ### Example Usage of UnorientedQuad Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/types.md Demonstrates creating an UnorientedQuad instance. This quad covers a 5x3 region starting at coordinates (10, 20, 30). ```rust use block_mesh::UnorientedQuad; let quad = UnorientedQuad { minimum: [10, 20, 30], width: 5, height: 3, }; // Quad covers a 5×3 region starting at (10, 20, 30) ``` -------------------------------- ### Example Usage of ndshape::ConstShape3u32 Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/module-reference.md Demonstrates how to define and use a fixed-size 3D shape with ndshape. ```rust use ndshape::{ConstShape, ConstShape3u32}; type MyShape = ConstShape3u32<18, 18, 18>; let shape = MyShape {}; ``` -------------------------------- ### Implementing and Using a Custom Merge Strategy Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/merge-strategy.md Demonstrates how to define a custom merge strategy (`MyStrategy`) and use it with `greedy_quads_with_merge_strategy`. This example shows a strategy that results in no merging (1x1 quads). ```rust use block_mesh::{ greedy_quads_with_merge_strategy, GreedyQuadsBuffer, Voxel, VoxelVisibility, RIGHT_HANDED_Y_UP_CONFIG, MergeStrategy, FaceStrides }; use ndshape::{ConstShape, ConstShape3u32}; #[derive(Clone, Copy)] struct SimpleVoxel(bool); impl Voxel for SimpleVoxel { fn get_visibility(&self) -> VoxelVisibility { if self.0 { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } // Define custom strategy struct MyStrategy; impl MergeStrategy for MyStrategy { type Voxel = SimpleVoxel; unsafe fn find_quad( min_index: u32, max_width: u32, max_height: u32, _strides: &FaceStrides, _voxels: &[SimpleVoxel], _visited: &[bool], ) -> (u32, u32) { (1, 1) // No merging } } type ChunkShape = ConstShape3u32<18, 18, 18>; let voxels = vec![SimpleVoxel(true); ChunkShape::SIZE as usize]; let mut buffer = GreedyQuadsBuffer::new(voxels.len()); greedy_quads_with_merge_strategy::( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer, ); ``` -------------------------------- ### GreedyQuadsBuffer Initialization Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Demonstrates how to create a new GreedyQuadsBuffer instance with a given voxel array size. Ensure the size parameter accurately reflects the total number of voxels. ```rust use block_mesh::GreedyQuadsBuffer; let buffer = GreedyQuadsBuffer::new(18 * 18 * 18); // 5832 voxels ``` -------------------------------- ### AxisPermutation.axes Method Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Demonstrates how to retrieve the ordered list of axes for a given AxisPermutation. Requires importing AxisPermutation and Axis enums. ```rust use block_mesh::{AxisPermutation, Axis}; let perm = AxisPermutation::Zxy; assert_eq!(perm.axes(), [Axis::Z, Axis::X, Axis::Y]); ``` -------------------------------- ### Example Usage of visible_block_faces Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/meshing-algorithms.md Demonstrates how to use the visible_block_faces algorithm to generate quads from a simple voxel array. Ensure correct shape, bounds, and face configuration are provided. The output buffer will be populated with generated quads. ```rust use block_mesh::{ visible_block_faces, VoxelVisibility, Voxel, UnitQuadBuffer, RIGHT_HANDED_Y_UP_CONFIG }; use ndshape::{ConstShape, ConstShape3u32}; #[derive(Clone, Copy)] struct SimpleVoxel(bool); impl Voxel for SimpleVoxel { fn get_visibility(&self) -> VoxelVisibility { if self.0 { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } type ChunkShape = ConstShape3u32<18, 18, 18>; // 16 interior + 2 padding let voxels = [SimpleVoxel(true); ChunkShape::SIZE as usize]; let mut buffer = UnitQuadBuffer::new(); visible_block_faces( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer, ); println!("Generated {} quads", buffer.num_quads()); for (face_idx, quads) in buffer.groups.iter().enumerate() { println!("Face {}: {} quads", face_idx, quads.len()); } ``` -------------------------------- ### FaceStrides Usage Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/merge-strategy.md Demonstrates how to use FaceStrides to compute indices for neighboring voxels and the facing voxel. Assumes `face_strides` and `index` are already defined. ```rust let u_neighbor = index + face_strides.u_stride; let v_neighbor = index + face_strides.v_stride; let facing_voxel = index.wrapping_add(face_strides.visibility_offset); ``` -------------------------------- ### SignedAxis::from_vector Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Demonstrates creating SignedAxis variants from IVec3 vectors. Use this when converting a vector to a SignedAxis, ensuring the vector has only one non-zero component. ```rust use block_mesh::SignedAxis; use ilattice::glam::IVec3; assert_eq!(SignedAxis::from_vector(IVec3::new(1, 0, 0)), Some(SignedAxis::PosX)); assert_eq!(SignedAxis::from_vector(IVec3::new(0, -1, 0)), Some(SignedAxis::NegY)); assert_eq!(SignedAxis::from_vector(IVec3::new(1, 1, 0)), None); ``` -------------------------------- ### Using RIGHT_HANDED_Y_UP_CONFIG in Meshing Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Example demonstrating how to use the RIGHT_HANDED_Y_UP_CONFIG constant with visible_block_faces function for meshing operations. Ensure the necessary imports and data structures are available. ```rust use block_mesh::RIGHT_HANDED_Y_UP_CONFIG; // Use in meshing functions visible_block_faces( &voxels, &shape, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer, ); ``` -------------------------------- ### Create an UnorientedUnitQuad Instance Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Example of creating an instance of the UnorientedUnitQuad struct with specified minimum coordinates. ```rust use block_mesh::UnorientedUnitQuad; let unit_quad = UnorientedUnitQuad { minimum: [5, 10, 15], }; ``` -------------------------------- ### Example Usage of UnorientedUnitQuad Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/types.md Demonstrates creating an UnorientedUnitQuad instance. This represents a single voxel face at the specified coordinates. ```rust use block_mesh::UnorientedUnitQuad; let unit_quad = UnorientedUnitQuad { minimum: [5, 10, 15], }; // Represents the single voxel face at (5, 10, 15) ``` -------------------------------- ### Generate Voxel Mesh with Greedy Quads Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/README.md This example demonstrates how to use the `greedy_quads` algorithm to generate a voxel mesh. It defines a custom `BoolVoxel` type, initializes a 16^3 chunk with spherical data, and then generates quads using `GreedyQuadsBuffer`. This is suitable for generating optimized meshes where triangle count is important. ```rust use block_mesh::ndshape::{ConstShape, ConstShape3u32}; use block_mesh::{greedy_quads, GreedyQuadsBuffer, MergeVoxel, Voxel, VoxelVisibility, RIGHT_HANDED_Y_UP_CONFIG}; #[derive(Clone, Copy, Eq, PartialEq)] struct BoolVoxel(bool); const EMPTY: BoolVoxel = BoolVoxel(false); const FULL: BoolVoxel = BoolVoxel(true); impl Voxel for BoolVoxel { fn get_visibility(&self) -> VoxelVisibility { if *self == EMPTY { VoxelVisibility::Empty } else { VoxelVisibility::Opaque } } } impl MergeVoxel for BoolVoxel { type MergeValue = Self; type MergeValueFacingNeighbour = Self; fn merge_value(&self) -> Self::MergeValue { *self } fn merge_value_facing_neighbour(&self) -> Self::MergeValueFacingNeighbour { *self } } // A 16^3 chunk with 1-voxel boundary padding. type ChunkShape = ConstShape3u32<18, 18, 18>; // This chunk will cover just a single octant of a sphere SDF (radius 15). let mut voxels = [EMPTY; ChunkShape::SIZE as usize]; for i in 0..ChunkShape::SIZE { let [x, y, z] = ChunkShape::delinearize(i); voxels[i as usize] = if ((x * x + y * y + z * z) as f32).sqrt() < 15.0 { FULL } else { EMPTY }; } let mut buffer = GreedyQuadsBuffer::new(voxels.len()); greedy_quads( &voxels, &ChunkShape {}, [0; 3], [17; 3], &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer ); // Some quads were generated. assert!(buffer.quads.num_quads() > 0); ``` -------------------------------- ### Create an UnorientedQuad Instance Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Example of creating an instance of the UnorientedQuad struct with specified minimum coordinates, width, and height. ```rust use block_mesh::UnorientedQuad; let quad = UnorientedQuad { minimum: [5, 10, 15], width: 4, height: 2, }; ``` -------------------------------- ### Voxel Array Layout for Meshing Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/quick-reference.md Illustrates the required 1-voxel padding for voxel arrays and how to define the shape for meshing. The example uses a ConstShape3u32 for an 18x18x18 array to represent a 16x16x16 interior. ```rust type Shape = ConstShape3u32<18, 18, 18>; // 16 + 2 let voxels = vec![...]; // 18 × 18 × 18 = 5832 voxels greedy_quads(&voxels, &Shape {}, [0; 3], [17; 3], ...); ``` -------------------------------- ### GreedyQuadsBuffer Reset Example Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Shows how to reset a GreedyQuadsBuffer to accommodate a different voxel array size, typically when moving to a new chunk. The buffer's internal state is adjusted accordingly. ```rust use block_mesh::GreedyQuadsBuffer; let mut buffer = GreedyQuadsBuffer::new(18 * 18 * 18); // ... greedy_quads call ... buffer.reset(20 * 20 * 20); // Reallocate for larger chunk ``` -------------------------------- ### Implementing Voxel Trait for Custom Block Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/voxel-traits.md Example implementation of the Voxel trait for a custom BlockVoxel struct. Determines visibility based on whether the block is solid. ```rust use block_mesh::{Voxel, VoxelVisibility}; #[derive(Clone, Copy)] struct BlockVoxel { is_solid: bool, } impl Voxel for BlockVoxel { fn get_visibility(&self) -> VoxelVisibility { if self.is_solid { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } ``` -------------------------------- ### find_quad Method Signature Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/merge-strategy.md The find_quad method calculates the width and height of a quad to be constructed starting at a given index. It is constrained by maximum dimensions and slice boundaries. ```rust unsafe fn find_quad( min_index: u32, max_width: u32, max_height: u32, face_strides: &FaceStrides, voxels: &[Self::Voxel], visited: &[bool], ) -> (u32, u32) where Self::Voxel: Voxel ``` -------------------------------- ### SignedAxis::signum Method Signature Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Signature for getting the sign of the axis. ```rust pub fn signum(&self) -> i32> ``` -------------------------------- ### SignedAxis::unsigned_axis Method Signature Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Signature for getting the unsigned axis component. ```rust pub fn unsigned_axis(&self) -> Axis> ``` -------------------------------- ### Custom Coordinate Systems Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Shows how to configure and use custom coordinate systems for meshing. ```rust use block_mesh_rs::geometry::QuadCoordinateConfig; // Define a custom configuration let custom_config = QuadCoordinateConfig { ... }; // Use this config when generating meshes or processing quads ``` -------------------------------- ### SignedAxis::get_unit_vector Method Signature Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Signature for getting the unit vector representation of a signed axis. ```rust pub fn get_unit_vector(&self) -> IVec3> ``` -------------------------------- ### Constructor: new Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Creates a new OrientedBlockFace with a specified normal sign and axis permutation. Use this to define a face's orientation. ```rust pub const fn new(n_sign: i32, permutation: AxisPermutation) -> Self ``` ```rust use block_mesh::{OrientedBlockFace, AxisPermutation}; let face = OrientedBlockFace::new(1, AxisPermutation::Xzy); ``` -------------------------------- ### Get Axis Permutation Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Returns the axis permutation type associated with the face, defining its orientation. ```rust pub fn permutation(&self) -> AxisPermutation ``` -------------------------------- ### Get Normal Sign Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Retrieves the sign of the surface normal for a face. This indicates the direction of the normal. ```rust pub fn n_sign(&self) -> i32 ``` -------------------------------- ### Translucent Voxel Handling Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Explains how to handle translucent voxels during the meshing process. ```rust use block_mesh_rs::meshing_algorithms::greedy_quads; use block_mesh_rs::buffers::GreedyQuadsBuffer; // Voxel data should indicate translucency let voxels = vec![...]; let mut buffer = GreedyQuadsBuffer::new(); greedy_quads(&voxels, &mut buffer); // Translucent quads will be generated and can be sorted or handled separately. ``` -------------------------------- ### Implementing MergeVoxel Trait for MaterialVoxel Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/voxel-traits.md Example implementation of both Voxel and MergeVoxel traits for a MaterialVoxel struct. Uses material_id for merging. ```rust use block_mesh::{MergeVoxel, Voxel, VoxelVisibility}; #[derive(Clone, Copy, Eq, PartialEq)] struct MaterialVoxel { material_id: u32, } impl Voxel for MaterialVoxel { fn get_visibility(&self) -> VoxelVisibility { VoxelVisibility::Opaque } } impl MergeVoxel for MaterialVoxel { type MergeValue = u32; type MergeValueFacingNeighbour = u32; fn merge_value(&self) -> Self::MergeValue { self.material_id } fn merge_value_facing_neighbour(&self) -> Self::MergeValueFacingNeighbour { self.material_id } } ``` -------------------------------- ### Buffer Management with GreedyQuadsBuffer Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/quick-reference.md Demonstrates how to create and reuse GreedyQuadsBuffer for processing chunks of voxels. The buffer should be created once and reset for each chunk. ```rust let mut buffer = GreedyQuadsBuffer::new(chunk_size); for voxels in chunks { buffer.reset(voxels.len()); greedy_quads(&voxels, &shape, [0; 3], [17; 3], &faces, &mut buffer); process(&buffer); } ``` -------------------------------- ### Axis Enum Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Represents one of the three spatial axes (X, Y, Z). Provides methods to get its index and unit vector. ```APIDOC ## Axis Enum ### Purpose Represents one of the three spatial axes. ### Methods #### `index` ```rust pub fn index(&self) -> usize ``` **Returns**: The array index for this axis (X=0, Y=1, Z=2). #### `get_unit_vector` ```rust pub const fn get_unit_vector(&self) -> UVec3 ``` **Returns**: A unit vector pointing in the positive direction of this axis. ``` -------------------------------- ### Axis Enum Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/types.md Represents one of the three spatial axes (X, Y, Z). Provides methods to get index and unit vector. ```rust pub enum Axis { X = 0, Y = 1, Z = 2, } ``` -------------------------------- ### Block Mesh RS Project File Structure Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Illustrates the directory layout of the Block Mesh RS project, showing the location of the main index file, README, and various reference and API documentation modules. ```text /workspace/home/output/ ├── INDEX.md (this file) ├── README.md ├── quick-reference.md ├── types.md ├── module-reference.md ├── common-patterns.md └── api-reference/ ├── voxel-traits.md ├── meshing-algorithms.md ├── geometry.md ├── buffers.md └── merge-strategy.md ``` -------------------------------- ### AxisPermutation.odd_with_normal_axis Method Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Returns the odd permutation of axes corresponding to a given normal axis. For example, an X normal maps to the Xzy permutation. ```rust pub const fn odd_with_normal_axis(axis: Axis) -> Self ``` -------------------------------- ### Basic Meshing with visible_block_faces Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/common-patterns.md Use this for simple and fast voxel meshing. The voxel array must be padded by 1 on all sides, and the shape should be (interior_size + 2) on each axis. Min and max coordinates define the interior region. ```Rust use block_mesh::{ visible_block_faces, VoxelVisibility, Voxel, UnitQuadBuffer, RIGHT_HANDED_Y_UP_CONFIG, }; use ndshape::{ConstShape, ConstShape3u32}; #[derive(Clone, Copy)] struct BlockVoxel(bool); impl Voxel for BlockVoxel { fn get_visibility(&self) -> VoxelVisibility { if self.0 { VoxelVisibility::Opaque } else { VoxelVisibility::Empty } } } // Define chunk size with 1-voxel padding on all sides type ChunkShape = ConstShape3u32<18, 18, 18>; // 16^3 interior + padding fn mesh_chunk(voxels: &[BlockVoxel]) -> UnitQuadBuffer { let mut buffer = UnitQuadBuffer::new(); visible_block_faces( voxels, &ChunkShape {{}}, [0; 3], // min (inclusive) [17; 3], // max (inclusive) &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer, ); buffer } fn main() { let voxels = vec![BlockVoxel(true); ChunkShape::SIZE as usize]; let buffer = mesh_chunk(&voxels); println!("Generated {} quads", buffer.num_quads()); } ``` -------------------------------- ### AxisPermutation.even_with_normal_axis Method Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Returns the even permutation of axes corresponding to a given normal axis. For example, an X normal maps to the Xyz permutation. ```rust pub const fn even_with_normal_axis(axis: Axis) -> Self ``` -------------------------------- ### Get Signed Normal Vector Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Returns the surface normal as a signed 3D integer vector. This vector points perpendicularly away from the face. ```rust pub fn signed_normal(&self) -> IVec3 ``` -------------------------------- ### Greedy Quad Meshing Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Illustrates how to use the `greedy_quads` function for optimized meshing with quad merging. ```rust use block_mesh_rs::meshing_algorithms::greedy_quads; let voxels = vec![...]; // Your voxel data let mut buffer = block_mesh_rs::buffers::GreedyQuadsBuffer::new(); greedy_quads(&voxels, &mut buffer); // Process the quads from the buffer ``` -------------------------------- ### Use Standard Right-Handed Y-Up Coordinate System Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/types.md Demonstrates how to use the predefined RIGHT_HANDED_Y_UP_CONFIG for a standard right-handed, Y-up coordinate system. This is commonly used in game development and meshing algorithms. ```rust use block_mesh::RIGHT_HANDED_Y_UP_CONFIG; let coord_system = RIGHT_HANDED_Y_UP_CONFIG; // Use coord_system.faces in meshing functions ``` -------------------------------- ### Basic Visible Block Faces Meshing Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Demonstrates the basic usage of the `visible_block_faces` function for meshing. ```rust use block_mesh_rs::meshing_algorithms::visible_block_faces; let voxels = vec![...]; // Your voxel data let faces = visible_block_faces(&voxels); // Process the generated faces ``` -------------------------------- ### Constructor for UnitQuadBuffer Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Creates a new UnitQuadBuffer. Initializes with six empty vectors, one for each cube face. ```rust pub fn new() -> Self ``` ```rust use block_mesh::UnitQuadBuffer; let buffer = UnitQuadBuffer::new(); ``` -------------------------------- ### Greedy Quads with Custom Merge Strategy Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Shows how to use `greedy_quads_with_merge_strategy` with a user-defined merge strategy. ```rust use block_mesh_rs::meshing_algorithms::greedy_quads_with_merge_strategy; use block_mesh_rs::merge_strategy::FaceStrides; // Assume MyMergeStrategy implements MergeStrategy trait struct MyMergeStrategy; impl MergeStrategy for MyMergeStrategy { ... } let voxels = vec![...]; let mut buffer = GreedyQuadsBuffer::new(); let strides = FaceStrides::new(...); // Configure strides appropriately greedy_quads_with_merge_strategy(&voxels, &strides, &mut buffer, &MyMergeStrategy); // Process quads from the buffer ``` -------------------------------- ### Initialize QuadBuffer Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Creates a new QuadBuffer instance. This buffer is used to collect quads generated by meshing algorithms, organized by cube face. ```rust use block_mesh::QuadBuffer; let buffer = QuadBuffer::new(); ``` -------------------------------- ### Processing Output Quads into Mesh Data Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Shows how to take the generated quads and convert them into mesh data for rendering or further processing. ```rust use block_mesh_rs::buffers::QuadBuffer; let mut buffer = QuadBuffer::new(); // ... populate buffer with quads ... let mesh_data = buffer.into_mesh_data(); // Use mesh_data for rendering ``` -------------------------------- ### Direct Imports from block_mesh Crate Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/types.md Lists common direct imports for voxel traits, geometry types, buffers, algorithms, and strategies from the block-mesh crate. ```rust // Direct imports from block_mesh use block_mesh:: // Voxel traits Voxel, VoxelVisibility, MergeVoxel, // Geometry types Axis, AxisPermutation, SignedAxis, UnorientedQuad, UnorientedUnitQuad, OrientedBlockFace, QuadCoordinateConfig, RIGHT_HANDED_Y_UP_CONFIG, // Buffers QuadBuffer, UnitQuadBuffer, GreedyQuadsBuffer, // Algorithms visible_block_faces, visible_block_faces_with_voxel_view, greedy_quads, greedy_quads_with_merge_strategy, // Strategies MergeStrategy, FaceStrides, ``` -------------------------------- ### Error Handling and Validation Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Illustrates how to handle potential errors and validate input data during meshing. ```rust // Functions may return Result types for error handling match visible_block_faces(&voxels) { Ok(faces) => { /* process faces */ }, Err(e) => { /* handle error */ } } ``` -------------------------------- ### MergeStrategy::find_quad Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/merge-strategy.md This method determines the dimensions (width and height) of a quad to be constructed starting from a given voxel index. It is a core part of the greedy meshing algorithm, allowing for customization of how voxels are merged into larger quads to optimize mesh generation. ```APIDOC ## MergeStrategy::find_quad ### Description Determines the width and height of the quad that should be constructed starting at `min_index`. This method is crucial for customizing the greedy meshing algorithm's quad merging behavior. ### Method `find_quad` ### Signature ```rust unsafe fn find_quad( min_index: u32, max_width: u32, max_height: u32, face_strides: &FaceStrides, voxels: &[Self::Voxel], visited: &[bool], ) -> (u32, u32) where Self::Voxel: Voxel; ``` ### Parameters #### Path Parameters * `min_index` (u32) - Required - Linear index of the minimum voxel for this quad. * `max_width` (u32) - Required - Maximum width the quad can be, constrained by the slice boundary. * `max_height` (u32) - Required - Maximum height the quad can be, constrained by the slice boundary. * `face_strides` (&FaceStrides) - Required - Stride information for navigating the voxel array. * `voxels` (&[Self::Voxel]) - Required - Complete voxel array, may be indexed with unchecked access. * `visited` (&[bool]) - Required - Bitmask of already-meshed voxels. ### Returns #### Success Response - `(u32, u32)` - A tuple `(width, height)` representing the dimensions of the quad. `1 <= width <= max_width` and `1 <= height <= max_height`. ### Safety This method is marked as `unsafe` because some implementations may use unchecked indexing for performance. Providing invalid parameters or incorrect bounds checking can lead to undefined behavior. Implementations must ensure bounds are validated before using unchecked access. ``` -------------------------------- ### GreedyQuadsBuffer::new Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Constructs a new GreedyQuadsBuffer with allocated space for a given number of voxels. This is the entry point for initializing the buffer used in greedy meshing. ```APIDOC ## GreedyQuadsBuffer::new ### Description Constructs a new buffer with allocated space for the greedy meshing algorithm. ### Method `new` ### Signature `pub fn new(size: usize) -> Self` ### Parameters #### Path Parameters - **size** (usize) - Required - Size of the voxel array (from `voxels_shape.size()`) ### Returns A new buffer with allocated space. ### Example ```rust use block_mesh::GreedyQuadsBuffer; let buffer = GreedyQuadsBuffer::new(18 * 18 * 18); // 5832 voxels ``` ``` -------------------------------- ### simple module functions Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/module-reference.md Provides functions for determining visible block faces using simple and advanced methods. ```APIDOC ## Simple Module Functions ### Description This module provides functions for determining visible block faces, offering both a basic and a more advanced approach using a voxel view. ### Functions - **visible_block_faces()** - Calculates visible block faces using a simple algorithm. - **visible_block_faces_with_voxel_view()** - Calculates visible block faces using a voxel view for more detailed control. ``` -------------------------------- ### QuadBuffer::new Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Constructs a new QuadBuffer with six empty vectors, one for each cube face, ready to store quads. ```APIDOC ## QuadBuffer::new ### Description Constructs a new QuadBuffer with six empty vectors, one for each cube face, ready to store quads. ### Method `new` ### Returns A new buffer with six empty vectors. ### Example ```rust use block_mesh::QuadBuffer; let buffer = QuadBuffer::new(); ``` ``` -------------------------------- ### Add block-mesh to Cargo.toml Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/quick-reference.md Add this dependency to your project's Cargo.toml file to use the block-mesh crate. ```toml [dependencies] block-mesh = "0.2" ``` -------------------------------- ### UnitQuadBuffer::new Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Constructs a new UnitQuadBuffer with six empty groups, ready to store unit quads for each cube face. ```APIDOC ## UnitQuadBuffer::new ### Description Constructs a new buffer with six empty vectors, one for each cube face. ### Returns A new `UnitQuadBuffer` instance. ### Example ```rust use block_mesh::UnitQuadBuffer; let buffer = UnitQuadBuffer::new(); ``` ``` -------------------------------- ### Buffer Reuse for Many Chunks Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Demonstrates the pattern of reusing mesh buffers for processing multiple chunks efficiently. ```rust use block_mesh_rs::buffers::QuadBuffer; let mut buffer = QuadBuffer::new(); for chunk in chunks { // Clear or reset the buffer for the new chunk buffer.clear(); // Populate buffer with quads for the current chunk // ... let mesh_data = buffer.into_mesh_data(); // Process mesh_data } ``` -------------------------------- ### Iterate Over UnitQuadBuffer Groups Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Demonstrates how to iterate through all the unit quads stored in the buffer, accessing them by face and then by individual quad. Useful for processing or rendering quads. ```rust use block_mesh::UnitQuadBuffer; let buffer = UnitQuadBuffer::new(); // Iterate over all groups for (face_idx, unit_quads) in buffer.groups.iter().enumerate() { for unit_quad in unit_quads { println!("Face {}: voxel at {:?}", face_idx, unit_quad.minimum); } } ``` -------------------------------- ### Iterate Over QuadBuffer Groups Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Demonstrates how to iterate through all face groups and individual quads within a QuadBuffer. This pattern is useful for processing or inspecting the collected geometry. ```rust use block_mesh::QuadBuffer; let buffer = QuadBuffer::new(); // Iterate over all groups for (face_idx, quads) in buffer.groups.iter().enumerate() { println!("Face {}: {} quads", face_idx, quads.len()); for quad in quads { println!(" Quad at {:?}, size {}x{}", quad.minimum, quad.width, quad.height); } } // Process a specific face if let Some(quads) = buffer.groups.get(3) { // Face 3 (e.g., +X) for quad in quads { // Process... } } ``` -------------------------------- ### SignedAxis::new Method Signature Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Signature for creating a SignedAxis from a sign and an Axis. ```rust pub fn new(sign: i32, axis: Axis) -> Self> ``` -------------------------------- ### Custom Voxel View for Visibility Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/quick-reference.md Shows how to implement a custom voxel view for determining face visibility. The MyView struct determines visibility based on the voxel's data, and the visible_block_faces_with_voxel_view function uses this view. ```rust struct MyVoxel { data: u32 } struct MyView { visible: bool } impl From<&MyVoxel> for MyView { fn from(v: &MyVoxel) -> Self { MyView { visible: v.data != 0 } } } visible_block_faces_with_voxel_view::( &voxels, &shape, [0; 3], [17; 3], &faces, &mut buffer ); ``` -------------------------------- ### Method: quad_mesh_positions Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/geometry.md Calculates the 4 vertex positions for rendering a quad, scaled by the voxel size. Returns positions as [x, y, z] arrays. ```rust pub fn quad_mesh_positions(&self, quad: &UnorientedQuad, voxel_size: f32) -> [[f32; 3]; 4] ``` ```rust use block_mesh::{UnorientedQuad, OrientedBlockFace, AxisPermutation}; let face = OrientedBlockFace::new(1, AxisPermutation::Xyz); let quad = UnorientedQuad { minimum: [0, 0, 0], width: 1, height: 1, }; let positions = face.quad_mesh_positions(&quad, 1.0); // positions[0] = [0.0, 0.0, 1.0] // positions[3] = [1.0, 1.0, 2.0] ``` -------------------------------- ### greedy module functions Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/module-reference.md Contains functions for the greedy meshing algorithm, including merging strategies and quad generation. ```APIDOC ## Greedy Module Functions ### Description This module implements the greedy meshing algorithm, which efficiently generates quads by merging adjacent faces. It includes functionalities for defining merge strategies and generating greedy quads. ### Functions - **greedy_quads()** - Generates quads using the greedy meshing algorithm. - **greedy_quads_with_merge_strategy()** - Generates quads using the greedy meshing algorithm with a specified merge strategy. ### Traits - **MergeStrategy** - Trait for defining custom merging logic. - **MergeVoxel** - Trait re-exported for use with the greedy algorithm. ``` -------------------------------- ### Visible Block Faces with Custom Voxel Type Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/INDEX.md Demonstrates using `visible_block_faces_with_voxel_view` with a custom voxel type. ```rust use block_mesh_rs::meshing_algorithms::visible_block_faces_with_voxel_view; use block_mesh_rs::voxel_traits::Voxel; // Define your custom voxel type that implements Voxel trait struct MyVoxel { ... } impl Voxel for MyVoxel { ... } let voxels: Vec = vec![...]; let faces = visible_block_faces_with_voxel_view(&voxels); // Process the generated faces ``` -------------------------------- ### GreedyQuadsBuffer Constructor Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/api-reference/buffers.md Initializes a new GreedyQuadsBuffer with a specified size for the voxel array. This is used to pre-allocate the necessary space for quads and internal tracking. ```rust pub fn new(size: usize) -> Self> ``` -------------------------------- ### Define Quad Coordinate System Configuration Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/types.md Defines the complete coordinate system for a cube, including the orientation of each of the six faces and rules for U-coordinate flipping. This configuration is crucial for correctly orienting textures and defining the output coordinate system for meshing functions. ```rust pub struct QuadCoordinateConfig { pub faces: [OrientedBlockFace; 6], pub u_flip_face: Axis, } ``` -------------------------------- ### Render Quads by Material Source: https://github.com/bonsairobo/block-mesh-rs/blob/main/_autodocs/common-patterns.md Renders quads grouped by material and face. This function processes the generated quads, assigns them to materials, and prints the number of triangles per material. It uses face index to apply correct orientation. ```rust use block_mesh::RIGHT_HANDED_Y_UP_CONFIG; use std::collections::HashMap; // Assuming MaterialId, TexturedVoxel, ChunkShape, and GreedyQuadsBuffer are defined as above fn render_by_material( buffer: &GreedyQuadsBuffer, voxels: &[TexturedVoxel], ) { let mut by_material: HashMap> = HashMap::new(); for (face_idx, quads) in buffer.quads.groups.iter().enumerate() { let face = &RIGHT_HANDED_Y_UP_CONFIG.faces[face_idx]; let mut current_index = 0u32; for quad in quads { let material = MaterialId(1); // Look up from voxels if needed let indices = face.quad_mesh_indices(current_index); by_material.entry(material) .or_insert_with(Vec::new) .extend_from_slice(&indices); current_index += 4; } } for (material, indices) in by_material { println!("Material {:?}: {} triangles", material, indices.len() / 3); // Render with the appropriate material/texture } } ```