This commit is contained in:
1 parent
293811aecd
commit
d1a56f77cc
23 files changed
+1730
-62
No files matched your search
@@ -856,6 +856,30 @@ impl BrushDesc {
|
||||
}
|
||||
|
||||
pub const TERRAIN_SCHEMA_VERSION: u32 = 1;
|
||||
pub const TERRAIN_MATERIAL_LAYER_LIMIT: usize = 4;
|
||||
|
||||
fn default_terrain_layer_uv_scale() -> f32 {
|
||||
8.0
|
||||
}
|
||||
|
||||
/// One shared project material assigned to a terrain blend channel.
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TerrainMaterialLayer {
|
||||
#[serde(default)]
|
||||
pub material: Option<EditorAssetRef>,
|
||||
#[serde(default = "default_terrain_layer_uv_scale")]
|
||||
pub uv_scale: f32,
|
||||
}
|
||||
|
||||
impl Default for TerrainMaterialLayer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
material: None,
|
||||
uv_scale: default_terrain_layer_uv_scale(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent height-grid terrain authoring data. Hydration partitions the grid into generated
|
||||
/// render/collider chunks; saved scenes retain only this descriptor.
|
||||
@@ -876,6 +900,13 @@ pub struct TerrainDesc {
|
||||
pub chunk_quads: u32,
|
||||
#[serde(default)]
|
||||
pub base_material: Option<EditorAssetRef>,
|
||||
/// Up to four project Material/Material Instance assignments. Empty retains the legacy
|
||||
/// `base_material` path and an empty weight map means 100% channel zero.
|
||||
#[serde(default)]
|
||||
pub material_layers: Vec<TerrainMaterialLayer>,
|
||||
/// RGBA8 weights per height sample. Channels correspond to `material_layers`.
|
||||
#[serde(default)]
|
||||
pub material_weights: Vec<[u8; TERRAIN_MATERIAL_LAYER_LIMIT]>,
|
||||
#[serde(default = "default_true")]
|
||||
pub generate_colliders: bool,
|
||||
#[serde(default = "default_true")]
|
||||
@@ -894,6 +925,8 @@ impl Default for TerrainDesc {
|
||||
height_scale: default_terrain_height_scale(),
|
||||
chunk_quads: default_terrain_chunk_quads(),
|
||||
base_material: None,
|
||||
material_layers: Vec::new(),
|
||||
material_weights: Vec::new(),
|
||||
generate_colliders: true,
|
||||
cast_shadows: true,
|
||||
receive_shadows: true,
|
||||
@@ -933,6 +966,44 @@ impl TerrainDesc {
|
||||
if self.heights.iter().any(|height| !height.is_finite()) {
|
||||
return Err("terrain height samples must all be finite".into());
|
||||
}
|
||||
if self.material_layers.len() > TERRAIN_MATERIAL_LAYER_LIMIT {
|
||||
return Err(format!(
|
||||
"terrain supports at most {TERRAIN_MATERIAL_LAYER_LIMIT} material layers"
|
||||
));
|
||||
}
|
||||
for (index, layer) in self.material_layers.iter().enumerate() {
|
||||
if !layer.uv_scale.is_finite() || layer.uv_scale <= 0.0 {
|
||||
return Err(format!(
|
||||
"terrain material layer {} UV scale must be finite and positive",
|
||||
index + 1
|
||||
));
|
||||
}
|
||||
}
|
||||
if !self.material_weights.is_empty() {
|
||||
if self.material_weights.len() != expected {
|
||||
return Err(format!(
|
||||
"terrain resolution {} requires {expected} material weights, found {}",
|
||||
self.resolution,
|
||||
self.material_weights.len()
|
||||
));
|
||||
}
|
||||
if self
|
||||
.material_weights
|
||||
.iter()
|
||||
.any(|weights| weights.iter().copied().map(u16::from).sum::<u16>() != 255)
|
||||
{
|
||||
return Err("terrain material weights must sum to 255 at every sample".into());
|
||||
}
|
||||
let active_channels = self.material_layers.len().max(1);
|
||||
if self.material_weights.iter().any(|weights| {
|
||||
weights
|
||||
.iter()
|
||||
.skip(active_channels)
|
||||
.any(|weight| *weight != 0)
|
||||
}) {
|
||||
return Err("terrain material weights use an unassigned layer channel".into());
|
||||
}
|
||||
}
|
||||
if !self.sample_spacing.is_finite() || self.sample_spacing <= 0.0 {
|
||||
return Err("terrain sample spacing must be finite and positive".into());
|
||||
}
|
||||
@@ -947,6 +1018,39 @@ impl TerrainDesc {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Material channels used by hydration, including the legacy base-material fallback.
|
||||
pub fn effective_material_layers(&self) -> Vec<TerrainMaterialLayer> {
|
||||
if !self.material_layers.is_empty() {
|
||||
return self.material_layers.clone();
|
||||
}
|
||||
self.base_material
|
||||
.clone()
|
||||
.map(|material| TerrainMaterialLayer {
|
||||
material: Some(material),
|
||||
..Default::default()
|
||||
})
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Material weights for one sample, normalized for vertex transport.
|
||||
pub fn normalized_material_weights(&self, sample_index: usize) -> [f32; 4] {
|
||||
let weights = self
|
||||
.material_weights
|
||||
.get(sample_index)
|
||||
.copied()
|
||||
.unwrap_or([255, 0, 0, 0]);
|
||||
weights.map(|weight| f32::from(weight) / 255.0)
|
||||
}
|
||||
|
||||
/// Materializes the implicit channel-zero map before an editor paint operation.
|
||||
pub fn ensure_material_weights(&mut self) {
|
||||
let expected = self.resolution as usize * self.resolution as usize;
|
||||
if self.material_weights.len() != expected {
|
||||
self.material_weights = vec![[255, 0, 0, 0]; expected];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_terrain_schema_version() -> u32 {
|
||||
|
||||
@@ -8,7 +8,8 @@ use bevy::prelude::*;
|
||||
|
||||
use crate::{
|
||||
authoring_component_active, load_resolved_material_from_path, AuthoringComponentStates,
|
||||
InspectorOrder, LevelObject, RaytracingExcluded, TerrainDesc, COMPONENT_TERRAIN_DESC,
|
||||
HydratedTerrainMaterialBinding, InspectorOrder, LevelObject, RaytracingExcluded, TerrainDesc,
|
||||
COMPONENT_TERRAIN_DESC,
|
||||
};
|
||||
|
||||
use super::materials::material_from_desc;
|
||||
@@ -96,9 +97,10 @@ pub fn spawn_terrain_chunks(
|
||||
return;
|
||||
}
|
||||
|
||||
let material = terrain
|
||||
.base_material
|
||||
.as_ref()
|
||||
let effective_layers = terrain.effective_material_layers();
|
||||
let material = effective_layers
|
||||
.first()
|
||||
.and_then(|layer| layer.material.as_ref())
|
||||
.and_then(|reference| reference.source_path.as_deref())
|
||||
.and_then(|path| match load_resolved_material_from_path(path) {
|
||||
Ok((desc, _)) => Some(material_from_desc(asset_server, &desc)),
|
||||
@@ -135,6 +137,10 @@ pub fn spawn_terrain_chunks(
|
||||
Name::new(format!("Terrain Chunk {chunk_x},{chunk_z}")),
|
||||
Mesh3d(mesh),
|
||||
MeshMaterial3d(material.clone()),
|
||||
HydratedTerrainMaterialBinding {
|
||||
owner,
|
||||
layers: terrain.effective_material_layers(),
|
||||
},
|
||||
Transform::default(),
|
||||
Visibility::Visible,
|
||||
RaytracingExcluded,
|
||||
@@ -188,6 +194,7 @@ pub fn terrain_chunk_mesh(
|
||||
let mut positions = Vec::with_capacity((width * depth) as usize);
|
||||
let mut normals = Vec::with_capacity((width * depth) as usize);
|
||||
let mut uvs = Vec::with_capacity((width * depth) as usize);
|
||||
let mut colors = Vec::with_capacity((width * depth) as usize);
|
||||
let quad_count = (terrain.resolution - 1) as f32;
|
||||
let half_extent = quad_count * terrain.sample_spacing * 0.5;
|
||||
|
||||
@@ -209,6 +216,7 @@ pub fn terrain_chunk_mesh(
|
||||
]);
|
||||
normals.push(normal.to_array());
|
||||
uvs.push([x as f32 / quad_count, z as f32 / quad_count]);
|
||||
colors.push(terrain.normalized_material_weights((z * terrain.resolution + x) as usize));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,6 +238,7 @@ pub fn terrain_chunk_mesh(
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors);
|
||||
mesh.insert_indices(Indices::U32(indices));
|
||||
if let Err(error) = mesh.generate_tangents() {
|
||||
warn!("Terrain chunk tangent generation failed: {error:?}");
|
||||
@@ -264,12 +273,61 @@ mod tests {
|
||||
let mut terrain = TerrainDesc::flat(5);
|
||||
terrain.heights[12] = 0.75;
|
||||
terrain.sample_spacing = 2.0;
|
||||
terrain.material_layers = vec![
|
||||
crate::TerrainMaterialLayer {
|
||||
material: Some(crate::EditorAssetRef::new(
|
||||
"ground",
|
||||
"material:source",
|
||||
"Ground",
|
||||
)),
|
||||
uv_scale: 6.0,
|
||||
},
|
||||
crate::TerrainMaterialLayer {
|
||||
material: Some(crate::EditorAssetRef::new(
|
||||
"rock",
|
||||
"material:source",
|
||||
"Rock",
|
||||
)),
|
||||
uv_scale: 12.0,
|
||||
},
|
||||
];
|
||||
terrain.ensure_material_weights();
|
||||
terrain.material_weights[12] = [64, 191, 0, 0];
|
||||
let text = ron::to_string(&terrain).unwrap();
|
||||
let restored: TerrainDesc = ron::from_str(&text).unwrap();
|
||||
assert_eq!(restored, terrain);
|
||||
assert!(restored.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_mesh_transports_normalized_material_weights_as_vertex_colors() {
|
||||
let mut terrain = TerrainDesc::flat(3);
|
||||
terrain.ensure_material_weights();
|
||||
terrain.material_weights[4] = [64, 191, 0, 0];
|
||||
let mesh = terrain_chunk_mesh(&terrain, 0, 0, 2, 2).unwrap();
|
||||
let Some(bevy::mesh::VertexAttributeValues::Float32x4(colors)) =
|
||||
mesh.attribute(Mesh::ATTRIBUTE_COLOR)
|
||||
else {
|
||||
panic!("terrain chunks should carry RGBA layer weights");
|
||||
};
|
||||
assert_eq!(colors.len(), 9);
|
||||
assert!((colors[4][0] - 64.0 / 255.0).abs() < 0.0001);
|
||||
assert!((colors[4][1] - 191.0 / 255.0).abs() < 0.0001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_rejects_non_normalized_material_weights() {
|
||||
let mut terrain = TerrainDesc::flat(3);
|
||||
terrain.material_weights = vec![[128, 128, 0, 0]; 9];
|
||||
assert!(terrain.validate().unwrap_err().contains("sum to 255"));
|
||||
|
||||
terrain.material_weights = vec![[127, 0, 128, 0]; 9];
|
||||
assert!(terrain
|
||||
.validate()
|
||||
.unwrap_err()
|
||||
.contains("unassigned layer channel"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hydration_generates_runtime_only_chunks_and_cleans_up() {
|
||||
let mut app = App::new();
|
||||
|
||||
@@ -114,6 +114,7 @@ impl Plugin for SharedTypesPlugin {
|
||||
.register_type::<PrimitiveShape>()
|
||||
.register_type::<BrushDesc>()
|
||||
.register_type::<TerrainDesc>()
|
||||
.register_type::<TerrainMaterialLayer>()
|
||||
.register_type::<BrushKind>()
|
||||
.register_type::<BrushPlaneDesc>()
|
||||
.register_type::<BrushFaceDesc>()
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ComponentInstanceId, EditorAssetRef, MaterialParameter, MaterialTextureBinding};
|
||||
use crate::{
|
||||
ComponentInstanceId, EditorAssetRef, MaterialParameter, MaterialTextureBinding,
|
||||
TerrainMaterialLayer,
|
||||
};
|
||||
|
||||
/// A stable reference to a project material, material instance, or imported material subasset.
|
||||
///
|
||||
@@ -112,6 +115,23 @@ pub struct HydratedRendererMaterialBinding {
|
||||
pub effective_material: Option<MaterialRef>,
|
||||
}
|
||||
|
||||
/// Runtime ownership marker consumed by the project terrain-layer renderer.
|
||||
#[derive(Component, Reflect, Debug, Clone, PartialEq)]
|
||||
#[reflect(Component, Default, Debug, PartialEq)]
|
||||
pub struct HydratedTerrainMaterialBinding {
|
||||
pub owner: Entity,
|
||||
pub layers: Vec<TerrainMaterialLayer>,
|
||||
}
|
||||
|
||||
impl Default for HydratedTerrainMaterialBinding {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
owner: Entity::PLACEHOLDER,
|
||||
layers: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in new issue
Block a user