Skip to main content

voxel_framework/render/
material.rs

1//! Shared material and rendering components for voxel chunks.
2//!
3//! Provides two rendering paths for voxel chunks:
4//!
5//! 1. **Texture array path** (opt-in) — when [`ChunkTextureArray`] is inserted
6//!    as a resource before the plugin initialises, chunks are rendered with
7//!    [`ChunkMaterial`], a custom PBR material that samples a `texture_2d_array`.
8//!    The embedded WGSL shader applies per-vertex AO and simple diffuse lighting.
9//!
10//! 2. **Fallback path** (default) — when [`ChunkTextureArray`] is absent, chunks
11//!    use a shared [`bevy::pbr::StandardMaterial`] with vertex colors. This path
12//!    requires no texture assets and is compatible with all `VoxelType` palettes.
13
14use bevy::asset::RenderAssetUsages;
15use bevy::math::bounding::Aabb3d;
16use bevy::mesh::MeshVertexBufferLayoutRef;
17use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MeshPipelineKey};
18use bevy::prelude::*;
19use bevy::render::alpha::AlphaMode;
20use bevy::render::render_resource::{
21    AsBindGroup, RenderPipelineDescriptor, SpecializedMeshPipelineError,
22};
23use bevy::shader::ShaderRef;
24
25use crate::mesh::ATTRIBUTE_TEXTURE_LAYER;
26
27// ─── ChunkMaterial (texture array path) ───────────────────────────────────────
28
29/// Custom chunk material that samples a GPU `texture_2d_array`.
30///
31/// Register this via [`ChunkTextureArray`] before adding [`super::RenderPlugin`].
32/// The embedded WGSL shader multiplies the sampled texture color by the
33/// per-vertex AO value (stored in `ATTRIBUTE_COLOR`) and applies simple diffuse
34/// lighting with a fixed sun direction.
35///
36/// # Shader bindings
37///
38/// | Binding | Name              | Type                  |
39/// |---------|-------------------|-----------------------|
40/// | 0       | `texture_array`   | `texture_2d_array<f32>` |
41/// | 1       | `texture_sampler` | `sampler`             |
42///
43/// # Vertex attributes
44///
45/// | Location | Attribute              | Type       |
46/// |----------|------------------------|------------|
47/// | 0        | `ATTRIBUTE_POSITION`   | `Float32x3` |
48/// | 1        | `ATTRIBUTE_NORMAL`     | `Float32x3` |
49/// | 2        | `ATTRIBUTE_UV_0`       | `Float32x2` |
50/// | 3        | `ATTRIBUTE_COLOR`      | `Float32x4` |
51/// | 4        | `ATTRIBUTE_TEXTURE_LAYER` | `Uint32` |
52#[derive(Asset, TypePath, AsBindGroup, Clone)]
53pub struct ChunkMaterial {
54    /// Handle to the assembled texture array image (all voxel layers stacked).
55    #[texture(0, sample_type = "float", dimension = "2d_array")]
56    #[sampler(1)]
57    pub texture_array: Handle<Image>,
58}
59
60impl Material for ChunkMaterial {
61    fn vertex_shader() -> ShaderRef {
62        "embedded://voxel_framework/render/chunk.wgsl".into()
63    }
64
65    fn fragment_shader() -> ShaderRef {
66        "embedded://voxel_framework/render/chunk.wgsl".into()
67    }
68
69    fn specialize(
70        _pipeline: &MaterialPipeline,
71        descriptor: &mut RenderPipelineDescriptor,
72        layout: &MeshVertexBufferLayoutRef,
73        key: MaterialPipelineKey<Self>,
74    ) -> Result<(), SpecializedMeshPipelineError> {
75        // The prepass pipelines (depth, normal, motion-vector) use Bevy's
76        // built-in prepass vertex shader, which has its own vertex attribute
77        // expectations. Don't override the vertex buffer layout for them —
78        // Bevy sets it up correctly. Our custom layout is only needed for the
79        // main pass where chunk.wgsl's vertex function runs.
80        let is_prepass = key.mesh_key.intersects(
81            MeshPipelineKey::DEPTH_PREPASS
82                | MeshPipelineKey::NORMAL_PREPASS
83                | MeshPipelineKey::MOTION_VECTOR_PREPASS,
84        );
85        if is_prepass {
86            return Ok(());
87        }
88
89        let vertex_layout = layout.0.get_layout(&[
90            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
91            Mesh::ATTRIBUTE_NORMAL.at_shader_location(1),
92            Mesh::ATTRIBUTE_UV_0.at_shader_location(2),
93            Mesh::ATTRIBUTE_COLOR.at_shader_location(3),
94            ATTRIBUTE_TEXTURE_LAYER.at_shader_location(4),
95        ])?;
96        descriptor.vertex.buffers = vec![vertex_layout];
97        Ok(())
98    }
99}
100
101// ─── ChunkTextureArray ────────────────────────────────────────────────────────
102
103/// Optional resource that opts chunks into the texture-array rendering path.
104///
105/// Insert this resource before adding [`super::RenderPlugin`]. The plugin reads
106/// it during startup to create a [`ChunkMaterial`] handle that is shared across
107/// all chunk entities.
108///
109/// When this resource is absent the plugin falls back to [`bevy::pbr::StandardMaterial`]
110/// with vertex colors, which requires no texture setup.
111///
112/// # Example
113///
114/// ```rust,no_run
115/// use bevy::prelude::*;
116/// use voxel_framework::render::ChunkTextureArray;
117///
118/// let mut app = App::new();
119/// app.add_plugins(MinimalPlugins).init_asset::<Image>();
120/// let my_texture_array_handle: Handle<Image> = Handle::default();
121///
122/// // In your Bevy app setup, before adding VoxelCorePlugin / VoxelPlugin:
123/// app.insert_resource(ChunkTextureArray {
124///     handle: my_texture_array_handle,
125/// });
126/// ```
127#[derive(Resource)]
128pub struct ChunkTextureArray {
129    /// Handle to a `texture_2d_array` [`Image`] containing one layer per voxel type.
130    pub handle: Handle<Image>,
131}
132
133// ─── ChunkMaterialHandle ─────────────────────────────────────────────────────
134
135/// Internal resource that tracks which material handle all chunk entities share.
136///
137/// Populated by [`setup_chunk_material`] during [`bevy::prelude::Startup`].
138/// The `systems.rs` mesh system reads this to attach materials to chunk entities.
139#[derive(Resource, Default)]
140pub struct ChunkMaterialHandle {
141    /// Handle to the shared `StandardMaterial` (fallback path). `None` until setup runs.
142    pub standard: Option<Handle<StandardMaterial>>,
143    /// Handle to the shared `ChunkMaterial` (texture-array path). `None` unless
144    /// [`ChunkTextureArray`] was inserted before plugin setup.
145    pub custom: Option<Handle<ChunkMaterial>>,
146}
147
148// ─── ChunkMaterialConfig ─────────────────────────────────────────────────────
149
150/// Configuration for the fallback `StandardMaterial` chunk material.
151///
152/// Insert this resource before adding `RenderPlugin` to customise fallback
153/// material properties. If absent, sensible defaults are used (white base color,
154/// high roughness, no metallic).
155///
156/// This resource has no effect when [`ChunkTextureArray`] is present because
157/// the texture-array path uses the embedded WGSL shader.
158#[derive(Resource, Clone, Debug)]
159pub struct ChunkMaterialConfig {
160    /// Base color of the material. Vertex colors are multiplied by this value.
161    pub base_color: Color,
162    /// Perceptual roughness of the PBR material (0.0 = smooth, 1.0 = rough).
163    pub perceptual_roughness: f32,
164    /// Metallic factor (0.0 = dielectric, 1.0 = metal).
165    pub metallic: f32,
166    /// Reflectance at normal incidence for dielectric materials.
167    pub reflectance: f32,
168}
169
170impl Default for ChunkMaterialConfig {
171    fn default() -> Self {
172        Self {
173            base_color: Color::WHITE,
174            perceptual_roughness: 0.9,
175            metallic: 0.0,
176            reflectance: 0.1,
177        }
178    }
179}
180
181// ─── ChunkRendered ────────────────────────────────────────────────────────────
182
183/// Marker component indicating a chunk entity has been set up for rendering.
184///
185/// Inserted alongside `Mesh3d` and `MeshMaterial3d` to prevent duplicate
186/// render setup on the same entity.
187#[derive(Component)]
188pub struct ChunkRendered;
189
190// ─── setup_chunk_material ────────────────────────────────────────────────────
191
192/// Startup system that creates the shared chunk material.
193///
194/// If [`ChunkTextureArray`] is present, creates a [`ChunkMaterial`] backed by
195/// the provided texture array. Otherwise creates a `StandardMaterial` with
196/// vertex colors. The handle is stored in [`ChunkMaterialHandle`].
197pub fn setup_chunk_material(
198    mut standard_materials: ResMut<Assets<StandardMaterial>>,
199    mut chunk_materials: ResMut<Assets<ChunkMaterial>>,
200    mut handle: ResMut<ChunkMaterialHandle>,
201    config: Res<ChunkMaterialConfig>,
202    texture_array: Option<Res<ChunkTextureArray>>,
203) {
204    if let Some(tex) = texture_array {
205        // Texture-array path — use the embedded WGSL shader.
206        let mat = ChunkMaterial {
207            texture_array: tex.handle.clone(),
208        };
209        handle.custom = Some(chunk_materials.add(mat));
210    } else {
211        // Fallback path — standard PBR material with vertex colors.
212        // AlphaMode::Blend allows transparent voxels (e.g. water) to render
213        // correctly using the alpha channel baked into vertex colors.
214        let material = StandardMaterial {
215            base_color: config.base_color,
216            perceptual_roughness: config.perceptual_roughness,
217            metallic: config.metallic,
218            reflectance: config.reflectance,
219            alpha_mode: AlphaMode::Blend,
220            ..default()
221        };
222        handle.standard = Some(standard_materials.add(material));
223    }
224}
225
226// ─── chunk_aabb ──────────────────────────────────────────────────────────────
227
228/// Creates an axis-aligned bounding box sized for a standard voxel chunk.
229///
230/// The AABB is centered at half the chunk extent along each axis, covering
231/// the full 16x16x16 voxel region. This enables Bevy's built-in frustum
232/// culling to skip off-screen chunks.
233pub fn chunk_aabb() -> Aabb3d {
234    use bevy::math::Vec3A;
235    Aabb3d::new(Vec3A::splat(8.0), Vec3A::splat(8.0))
236}
237
238// ─── upgrade_to_texture_material ─────────────────────────────────────────────
239
240/// Upgrades existing chunk entities from `StandardMaterial` to `ChunkMaterial`
241/// once [`ChunkTextureArray`] becomes available (i.e. after async texture loading).
242///
243/// `setup_chunk_material` runs at `Startup` — before any textures have loaded —
244/// so it always falls back to `StandardMaterial`. This system runs every `Update`
245/// frame, does nothing until `ChunkTextureArray` is inserted AND
246/// `ChunkMaterialHandle.custom` is still `None`, then:
247///
248/// 1. Creates a `ChunkMaterial` from the texture array handle.
249/// 2. Stores it in `ChunkMaterialHandle.custom`.
250/// 3. Replaces `MeshMaterial3d<StandardMaterial>` with `MeshMaterial3d<ChunkMaterial>`
251///    on every entity that already has a [`ChunkRendered`] marker.
252///
253/// Because the greedy mesher always emits `ATTRIBUTE_TEXTURE_LAYER` vertices,
254/// existing meshes are already compatible with `ChunkMaterial` — no remesh needed.
255pub fn upgrade_to_texture_material(
256    mut commands: Commands,
257    mut chunk_materials: ResMut<Assets<ChunkMaterial>>,
258    mut handle: ResMut<ChunkMaterialHandle>,
259    texture_array: Option<Res<ChunkTextureArray>>,
260    rendered_chunks: Query<Entity, (With<ChunkRendered>, With<MeshMaterial3d<StandardMaterial>>)>,
261) {
262    // Only act once: when ChunkTextureArray appears but we haven't upgraded yet.
263    if handle.custom.is_some() {
264        return;
265    }
266    let Some(tex) = texture_array else {
267        return;
268    };
269
270    let mat = ChunkMaterial {
271        texture_array: tex.handle.clone(),
272    };
273    let mat_handle = chunk_materials.add(mat);
274    handle.custom = Some(mat_handle.clone());
275
276    // Swap the material on every already-rendered chunk.
277    for entity in &rendered_chunks {
278        commands
279            .entity(entity)
280            .remove::<MeshMaterial3d<StandardMaterial>>()
281            .insert(MeshMaterial3d(mat_handle.clone()));
282    }
283
284    eprintln!(
285        "voxel texture array active — {} chunk(s) upgraded to ChunkMaterial",
286        rendered_chunks.iter().count()
287    );
288}
289
290// ─── build_texture_array ─────────────────────────────────────────────────────
291
292/// Assembles N identically-sized [`Image`]s into a single GPU `texture_2d_array`.
293///
294/// Each input image is expected to be the same pixel dimensions and format.
295/// The images are stacked in the order provided: layer 0 = `images[0]`,
296/// layer 1 = `images[1]`, etc.
297///
298/// Returns an [`Image`] whose `texture_descriptor` is configured as a
299/// `D2` texture with `depth_or_array_layers = N`, suitable for binding as a
300/// `texture_2d_array` in a WGSL shader.
301///
302/// # Panics
303///
304/// Panics if `images` is empty or if images have different sizes / formats.
305pub fn build_texture_array(images: &[Image]) -> Image {
306    assert!(
307        !images.is_empty(),
308        "build_texture_array: must provide at least one image"
309    );
310    let first = &images[0];
311    let width = first.width();
312    let height = first.height();
313    let format = first.texture_descriptor.format;
314    let layers = images.len() as u32;
315
316    // Validate all images have matching dimensions and format.
317    for (i, img) in images.iter().enumerate() {
318        assert_eq!(img.width(), width, "image {i} width mismatch");
319        assert_eq!(img.height(), height, "image {i} height mismatch");
320        assert_eq!(
321            img.texture_descriptor.format, format,
322            "image {i} format mismatch"
323        );
324    }
325
326    // Concatenate raw pixel data from all layers.
327    let mut combined: Vec<u8> = Vec::new();
328    for img in images {
329        if let Some(data) = &img.data {
330            combined.extend_from_slice(data);
331        }
332    }
333
334    use bevy::render::render_resource::{
335        Extent3d, TextureDimension, TextureViewDescriptor, TextureViewDimension,
336    };
337
338    let size = Extent3d {
339        width,
340        height,
341        depth_or_array_layers: layers,
342    };
343
344    let mut array_image = Image::new(
345        size,
346        TextureDimension::D2,
347        combined,
348        format,
349        RenderAssetUsages::RENDER_WORLD,
350    );
351
352    // Tell Bevy/wgpu to interpret this as a 2D array texture view.
353    array_image.texture_view_descriptor = Some(TextureViewDescriptor {
354        label: Some("chunk_texture_array_view"),
355        dimension: Some(TextureViewDimension::D2Array),
356        ..Default::default()
357    });
358
359    array_image
360}