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, opaque rendering).
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 /// Alpha policy shared by all fallback chunks. Defaults to opaque so terrain
163 /// writes depth. Select `AlphaMode::Blend` explicitly for translucent palettes;
164 /// this does not split opaque/translucent geometry or sort individual faces.
165 pub alpha_mode: AlphaMode,
166 /// Perceptual roughness of the PBR material (0.0 = smooth, 1.0 = rough).
167 pub perceptual_roughness: f32,
168 /// Metallic factor (0.0 = dielectric, 1.0 = metal).
169 pub metallic: f32,
170 /// Reflectance at normal incidence for dielectric materials.
171 pub reflectance: f32,
172}
173
174impl Default for ChunkMaterialConfig {
175 fn default() -> Self {
176 Self {
177 base_color: Color::WHITE,
178 alpha_mode: AlphaMode::Opaque,
179 perceptual_roughness: 0.9,
180 metallic: 0.0,
181 reflectance: 0.1,
182 }
183 }
184}
185
186// ─── ChunkRendered ────────────────────────────────────────────────────────────
187
188/// Marker component indicating a chunk entity has been set up for rendering.
189///
190/// Inserted alongside `Mesh3d` and `MeshMaterial3d` to prevent duplicate
191/// render setup on the same entity.
192#[derive(Component)]
193pub struct ChunkRendered;
194
195// ─── setup_chunk_material ────────────────────────────────────────────────────
196
197/// Startup system that creates the shared chunk material.
198///
199/// If [`ChunkTextureArray`] is present, creates a [`ChunkMaterial`] backed by
200/// the provided texture array. Otherwise creates a `StandardMaterial` with
201/// vertex colors. The handle is stored in [`ChunkMaterialHandle`].
202pub fn setup_chunk_material(
203 mut standard_materials: ResMut<Assets<StandardMaterial>>,
204 mut chunk_materials: ResMut<Assets<ChunkMaterial>>,
205 mut handle: ResMut<ChunkMaterialHandle>,
206 config: Res<ChunkMaterialConfig>,
207 texture_array: Option<Res<ChunkTextureArray>>,
208) {
209 if let Some(tex) = texture_array {
210 // Texture-array path — use the embedded WGSL shader.
211 let mat = ChunkMaterial {
212 texture_array: tex.handle.clone(),
213 };
214 handle.custom = Some(chunk_materials.add(mat));
215 } else {
216 // Fallback path — standard PBR material with vertex colors.
217 // Opaque terrain must write depth even when every vertex has alpha 1.
218 // Translucent palettes can explicitly opt into a different alpha policy.
219 let material = StandardMaterial {
220 base_color: config.base_color,
221 perceptual_roughness: config.perceptual_roughness,
222 metallic: config.metallic,
223 reflectance: config.reflectance,
224 alpha_mode: config.alpha_mode,
225 ..default()
226 };
227 handle.standard = Some(standard_materials.add(material));
228 }
229}
230
231// ─── chunk_aabb ──────────────────────────────────────────────────────────────
232
233/// Creates an axis-aligned bounding box sized for a standard voxel chunk.
234///
235/// The AABB is centered at half the chunk extent along each axis, covering
236/// the full 16x16x16 voxel region. This enables Bevy's built-in frustum
237/// culling to skip off-screen chunks.
238pub fn chunk_aabb() -> Aabb3d {
239 use bevy::math::Vec3A;
240 Aabb3d::new(Vec3A::splat(8.0), Vec3A::splat(8.0))
241}
242
243// ─── upgrade_to_texture_material ─────────────────────────────────────────────
244
245/// Upgrades existing chunk entities from `StandardMaterial` to `ChunkMaterial`
246/// once [`ChunkTextureArray`] becomes available (i.e. after async texture loading).
247///
248/// `setup_chunk_material` runs at `Startup` — before any textures have loaded —
249/// so it always falls back to `StandardMaterial`. This system runs every `Update`
250/// frame, does nothing until `ChunkTextureArray` is inserted AND
251/// `ChunkMaterialHandle.custom` is still `None`, then:
252///
253/// 1. Creates a `ChunkMaterial` from the texture array handle.
254/// 2. Stores it in `ChunkMaterialHandle.custom`.
255/// 3. Replaces `MeshMaterial3d<StandardMaterial>` with `MeshMaterial3d<ChunkMaterial>`
256/// on every entity that already has a [`ChunkRendered`] marker.
257///
258/// Because the greedy mesher always emits `ATTRIBUTE_TEXTURE_LAYER` vertices,
259/// existing meshes are already compatible with `ChunkMaterial` — no remesh needed.
260pub fn upgrade_to_texture_material(
261 mut commands: Commands,
262 mut chunk_materials: ResMut<Assets<ChunkMaterial>>,
263 mut handle: ResMut<ChunkMaterialHandle>,
264 texture_array: Option<Res<ChunkTextureArray>>,
265 rendered_chunks: Query<Entity, (With<ChunkRendered>, With<MeshMaterial3d<StandardMaterial>>)>,
266) {
267 // Only act once: when ChunkTextureArray appears but we haven't upgraded yet.
268 if handle.custom.is_some() {
269 return;
270 }
271 let Some(tex) = texture_array else {
272 return;
273 };
274
275 let mat = ChunkMaterial {
276 texture_array: tex.handle.clone(),
277 };
278 let mat_handle = chunk_materials.add(mat);
279 handle.custom = Some(mat_handle.clone());
280
281 // Swap the material on every already-rendered chunk.
282 for entity in &rendered_chunks {
283 commands
284 .entity(entity)
285 .remove::<MeshMaterial3d<StandardMaterial>>()
286 .insert(MeshMaterial3d(mat_handle.clone()));
287 }
288
289 eprintln!(
290 "voxel texture array active — {} chunk(s) upgraded to ChunkMaterial",
291 rendered_chunks.iter().count()
292 );
293}
294
295// ─── build_texture_array ─────────────────────────────────────────────────────
296
297/// Assembles N identically-sized [`Image`]s into a single GPU `texture_2d_array`.
298///
299/// Each input image is expected to be the same pixel dimensions and format.
300/// The images are stacked in the order provided: layer 0 = `images[0]`,
301/// layer 1 = `images[1]`, etc.
302///
303/// Returns an [`Image`] whose `texture_descriptor` is configured as a
304/// `D2` texture with `depth_or_array_layers = N`, suitable for binding as a
305/// `texture_2d_array` in a WGSL shader.
306///
307/// # Panics
308///
309/// Panics if `images` is empty or if images have different sizes / formats.
310pub fn build_texture_array(images: &[Image]) -> Image {
311 assert!(
312 !images.is_empty(),
313 "build_texture_array: must provide at least one image"
314 );
315 let first = &images[0];
316 let width = first.width();
317 let height = first.height();
318 let format = first.texture_descriptor.format;
319 let layers = images.len() as u32;
320
321 // Validate all images have matching dimensions and format.
322 for (i, img) in images.iter().enumerate() {
323 assert_eq!(img.width(), width, "image {i} width mismatch");
324 assert_eq!(img.height(), height, "image {i} height mismatch");
325 assert_eq!(
326 img.texture_descriptor.format, format,
327 "image {i} format mismatch"
328 );
329 }
330
331 // Concatenate raw pixel data from all layers.
332 let mut combined: Vec<u8> = Vec::new();
333 for img in images {
334 if let Some(data) = &img.data {
335 combined.extend_from_slice(data);
336 }
337 }
338
339 use bevy::render::render_resource::{
340 Extent3d, TextureDimension, TextureViewDescriptor, TextureViewDimension,
341 };
342
343 let size = Extent3d {
344 width,
345 height,
346 depth_or_array_layers: layers,
347 };
348
349 let mut array_image = Image::new(
350 size,
351 TextureDimension::D2,
352 combined,
353 format,
354 RenderAssetUsages::RENDER_WORLD,
355 );
356
357 // Tell Bevy/wgpu to interpret this as a 2D array texture view.
358 array_image.texture_view_descriptor = Some(TextureViewDescriptor {
359 label: Some("chunk_texture_array_view"),
360 dimension: Some(TextureViewDimension::D2Array),
361 ..Default::default()
362 });
363
364 array_image
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370 use crate::{
371 chunk::Chunk,
372 mesh::generate_chunk_mesh,
373 voxel::{DefaultVoxel, VoxelType},
374 };
375 use bevy::mesh::VertexAttributeValues;
376
377 fn startup(config: ChunkMaterialConfig, texture: bool) -> App {
378 let mut app = App::new();
379 app.init_resource::<Assets<StandardMaterial>>()
380 .init_resource::<Assets<ChunkMaterial>>()
381 .init_resource::<ChunkMaterialHandle>()
382 .insert_resource(config)
383 .add_systems(Startup, setup_chunk_material);
384 if texture {
385 app.insert_resource(ChunkTextureArray {
386 handle: Handle::default(),
387 });
388 }
389 app.update();
390 app
391 }
392
393 #[test]
394 fn fallback_terrain_is_opaque_by_default() {
395 let app = startup(ChunkMaterialConfig::default(), false);
396 let handles = app.world().resource::<ChunkMaterialHandle>();
397 let materials = app.world().resource::<Assets<StandardMaterial>>();
398 let material = materials.get(handles.standard.as_ref().unwrap()).unwrap();
399 assert_eq!(material.alpha_mode, AlphaMode::Opaque);
400 assert!(handles.custom.is_none());
401 }
402
403 #[test]
404 fn default_palette_solids_are_opaque_and_air_has_no_geometry() {
405 for step in [1, 2] {
406 assert_eq!(
407 generate_chunk_mesh(&Chunk::<DefaultVoxel>::new(), step).count_vertices(),
408 0
409 );
410 for voxel in [
411 DefaultVoxel::Rock,
412 DefaultVoxel::IronOre,
413 DefaultVoxel::SiliconCrystal,
414 DefaultVoxel::RareMineral,
415 ] {
416 assert_eq!(voxel.color()[3], 1.0);
417 let mut chunk = Chunk::new();
418 chunk.set(0, 0, 0, voxel);
419 let mesh = generate_chunk_mesh(&chunk, step);
420 assert!(mesh.count_vertices() > 0);
421 let Some(VertexAttributeValues::Float32x4(colors)) =
422 mesh.attribute(Mesh::ATTRIBUTE_COLOR)
423 else {
424 panic!("expected vertex colors")
425 };
426 assert!(colors.iter().all(|color| color[3] == 1.0));
427 }
428 }
429 }
430 #[test]
431 fn fallback_honors_explicit_alpha_and_pbr_configuration() {
432 for alpha_mode in [AlphaMode::Blend, AlphaMode::Mask(0.4)] {
433 let config = ChunkMaterialConfig {
434 base_color: Color::srgba(0.2, 0.3, 0.4, 0.5),
435 alpha_mode,
436 perceptual_roughness: 0.6,
437 metallic: 0.7,
438 reflectance: 0.8,
439 };
440 let app = startup(config.clone(), false);
441 let handles = app.world().resource::<ChunkMaterialHandle>();
442 let materials = app.world().resource::<Assets<StandardMaterial>>();
443 let material = materials.get(handles.standard.as_ref().unwrap()).unwrap();
444 assert_eq!(material.alpha_mode, alpha_mode);
445 assert_eq!(material.base_color, config.base_color);
446 assert_eq!(material.perceptual_roughness, config.perceptual_roughness);
447 assert_eq!(material.metallic, config.metallic);
448 assert_eq!(material.reflectance, config.reflectance);
449 }
450 }
451
452 #[test]
453 fn texture_array_ignores_fallback_alpha_policy() {
454 let app = startup(
455 ChunkMaterialConfig {
456 alpha_mode: AlphaMode::Blend,
457 ..default()
458 },
459 true,
460 );
461 let handles = app.world().resource::<ChunkMaterialHandle>();
462 assert!(handles.standard.is_none());
463 let materials = app.world().resource::<Assets<ChunkMaterial>>();
464 let material = materials.get(handles.custom.as_ref().unwrap()).unwrap();
465 assert_eq!(material.alpha_mode(), AlphaMode::Opaque);
466 assert_eq!(material.texture_array, Handle::<Image>::default());
467 }
468}