This commit is contained in:
1 parent
cc6acb188d
commit
9f95ba3082
24 files changed
+891
-78
No files matched your search
@@ -0,0 +1,231 @@
|
||||
//! Convex brush hydration from authored face polygons.
|
||||
|
||||
use avian3d::prelude::ColliderConstructor;
|
||||
use bevy::asset::RenderAssetUsages;
|
||||
use bevy::light::{NotShadowCaster, NotShadowReceiver};
|
||||
use bevy::mesh::{Indices, PrimitiveTopology};
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::{
|
||||
inspector_component_active, BrushDesc, BrushFaceDesc, ColliderDesc, InspectorOrder,
|
||||
LevelObject, MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
|
||||
COMPONENT_MATERIAL_DESC,
|
||||
};
|
||||
|
||||
use super::materials::material_from_desc;
|
||||
|
||||
/// Runtime marker for generated brush render/collider children.
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, Copy)]
|
||||
#[reflect(Component, Default, Debug)]
|
||||
pub struct HydratedBrushMesh;
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn hydrate_brushes(
|
||||
mut commands: Commands,
|
||||
asset_server: Res<AssetServer>,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||
brushes: Query<
|
||||
(
|
||||
Entity,
|
||||
&BrushDesc,
|
||||
Option<&MaterialDesc>,
|
||||
Option<&ColliderDesc>,
|
||||
Option<&InspectorOrder>,
|
||||
),
|
||||
(
|
||||
With<LevelObject>,
|
||||
Or<(
|
||||
Added<BrushDesc>,
|
||||
Changed<BrushDesc>,
|
||||
Changed<MaterialDesc>,
|
||||
Changed<ColliderDesc>,
|
||||
Changed<InspectorOrder>,
|
||||
)>,
|
||||
),
|
||||
>,
|
||||
children: Query<&Children>,
|
||||
generated_brushes: Query<(), With<HydratedBrushMesh>>,
|
||||
) {
|
||||
for (entity, brush, material, collider, order) in &brushes {
|
||||
despawn_brush_mesh(&mut commands, entity, &children, &generated_brushes);
|
||||
if !inspector_component_active(order, COMPONENT_BRUSH_DESC) {
|
||||
continue;
|
||||
}
|
||||
spawn_brush_mesh(
|
||||
&mut commands,
|
||||
&asset_server,
|
||||
&mut meshes,
|
||||
&mut materials,
|
||||
entity,
|
||||
brush,
|
||||
material.filter(|_| inspector_component_active(order, COMPONENT_MATERIAL_DESC)),
|
||||
collider.filter(|_| inspector_component_active(order, COMPONENT_COLLIDER_DESC)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn_brush_mesh(
|
||||
commands: &mut Commands,
|
||||
asset_server: &AssetServer,
|
||||
meshes: &mut Assets<Mesh>,
|
||||
materials: &mut Assets<StandardMaterial>,
|
||||
parent: Entity,
|
||||
brush: &BrushDesc,
|
||||
material: Option<&MaterialDesc>,
|
||||
collider: Option<&ColliderDesc>,
|
||||
) {
|
||||
let Some(mesh) = brush_mesh(brush) else {
|
||||
warn!("Brush hydration skipped invalid brush on {parent:?}");
|
||||
return;
|
||||
};
|
||||
let mesh = meshes.add(mesh);
|
||||
let material = material
|
||||
.map(|material| materials.add(material_from_desc(asset_server, material)))
|
||||
.unwrap_or_else(|| {
|
||||
materials.add(StandardMaterial {
|
||||
base_color: Color::srgb(0.64, 0.68, 0.72),
|
||||
perceptual_roughness: 0.8,
|
||||
..default()
|
||||
})
|
||||
});
|
||||
|
||||
let mut brush_child = commands.spawn((
|
||||
HydratedBrushMesh,
|
||||
Name::new("Hydrated Brush Mesh"),
|
||||
Mesh3d(mesh),
|
||||
MeshMaterial3d(material),
|
||||
Transform::default(),
|
||||
Visibility::Visible,
|
||||
ChildOf(parent),
|
||||
));
|
||||
if !brush.cast_shadows {
|
||||
brush_child.insert(NotShadowCaster);
|
||||
}
|
||||
if !brush.receive_shadows {
|
||||
brush_child.insert(NotShadowReceiver);
|
||||
}
|
||||
if collider.is_some_and(|collider| collider.enabled) {
|
||||
brush_child.insert(ColliderConstructor::TrimeshFromMesh);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn despawn_brush_mesh(
|
||||
commands: &mut Commands,
|
||||
entity: Entity,
|
||||
children: &Query<&Children>,
|
||||
generated_brushes: &Query<(), With<HydratedBrushMesh>>,
|
||||
) {
|
||||
let Ok(child_list) = children.get(entity) else {
|
||||
return;
|
||||
};
|
||||
for child in child_list.iter() {
|
||||
if generated_brushes.get(child).is_ok() {
|
||||
commands.entity(child).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn brush_mesh(brush: &BrushDesc) -> Option<Mesh> {
|
||||
let mut positions = Vec::<[f32; 3]>::new();
|
||||
let mut normals = Vec::<[f32; 3]>::new();
|
||||
let mut uvs = Vec::<[f32; 2]>::new();
|
||||
let mut indices = Vec::<u32>::new();
|
||||
|
||||
for face in &brush.faces {
|
||||
append_face(face, &mut positions, &mut normals, &mut uvs, &mut indices)?;
|
||||
}
|
||||
if positions.is_empty() || indices.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut mesh = Mesh::new(
|
||||
PrimitiveTopology::TriangleList,
|
||||
RenderAssetUsages::default(),
|
||||
);
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
|
||||
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
|
||||
mesh.insert_indices(Indices::U32(indices));
|
||||
if let Err(error) = mesh.generate_tangents() {
|
||||
warn!("Brush mesh is not Solari-compatible: failed to generate tangents: {error:?}");
|
||||
}
|
||||
Some(mesh)
|
||||
}
|
||||
|
||||
fn append_face(
|
||||
face: &BrushFaceDesc,
|
||||
positions: &mut Vec<[f32; 3]>,
|
||||
normals: &mut Vec<[f32; 3]>,
|
||||
uvs: &mut Vec<[f32; 2]>,
|
||||
indices: &mut Vec<u32>,
|
||||
) -> Option<()> {
|
||||
if face.vertices.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
if !face.vertices.iter().all(|vertex| vertex.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let normal = face.plane.normal.try_normalize()?;
|
||||
if !normal.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let base = u32::try_from(positions.len()).ok()?;
|
||||
let (u_axis, v_axis) = face_axes(normal);
|
||||
for vertex in &face.vertices {
|
||||
positions.push([vertex.x, vertex.y, vertex.z]);
|
||||
normals.push([normal.x, normal.y, normal.z]);
|
||||
let uv = Vec2::new(vertex.dot(u_axis), vertex.dot(v_axis)) * face.uv_scale + face.uv_offset;
|
||||
uvs.push([uv.x, uv.y]);
|
||||
}
|
||||
|
||||
let flip = (face.vertices[1] - face.vertices[0])
|
||||
.cross(face.vertices[2] - face.vertices[0])
|
||||
.dot(normal)
|
||||
< 0.0;
|
||||
for i in 1..(face.vertices.len() - 1) {
|
||||
let i = u32::try_from(i).ok()?;
|
||||
if flip {
|
||||
indices.extend_from_slice(&[base, base + i + 1, base + i]);
|
||||
} else {
|
||||
indices.extend_from_slice(&[base, base + i, base + i + 1]);
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn face_axes(normal: Vec3) -> (Vec3, Vec3) {
|
||||
let tangent_seed = if normal.y.abs() > 0.9 {
|
||||
Vec3::X
|
||||
} else {
|
||||
Vec3::Y
|
||||
};
|
||||
let u = tangent_seed.cross(normal).normalize_or_zero();
|
||||
let v = normal.cross(u).normalize_or_zero();
|
||||
(u, v)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::BrushDesc;
|
||||
|
||||
#[test]
|
||||
fn cube_brush_builds_triangle_mesh() {
|
||||
let mesh = brush_mesh(&BrushDesc::default()).expect("cube brush mesh");
|
||||
assert_eq!(mesh.primitive_topology(), PrimitiveTopology::TriangleList);
|
||||
assert!(mesh.attribute(Mesh::ATTRIBUTE_POSITION).is_some());
|
||||
assert!(mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_some());
|
||||
assert!(mesh.attribute(Mesh::ATTRIBUTE_UV_0).is_some());
|
||||
assert!(mesh.attribute(Mesh::ATTRIBUTE_TANGENT).is_some());
|
||||
assert!(matches!(mesh.indices(), Some(Indices::U32(indices)) if indices.len() == 36));
|
||||
assert!(mesh.enable_raytracing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_brush_returns_none() {
|
||||
let mut brush = BrushDesc::default();
|
||||
brush.faces[0].vertices.clear();
|
||||
assert!(brush_mesh(&brush).is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Generates runtime render/physics/light components from reflectable authoring data.
|
||||
|
||||
mod brushes;
|
||||
mod lights;
|
||||
mod materials;
|
||||
mod models;
|
||||
@@ -16,6 +17,7 @@ pub use strip::{strip_hydrated, strip_hydrated_entity};
|
||||
use bevy::ecs::system::SystemState;
|
||||
use bevy::prelude::*;
|
||||
|
||||
use brushes::{hydrate_brushes, spawn_brush_mesh, HydratedBrushMesh};
|
||||
use lights::{hydrate_lights, reconcile_missing_runtime_lights};
|
||||
use materials::hydrate_materials;
|
||||
pub use materials::material_from_desc;
|
||||
@@ -30,10 +32,10 @@ use static_meshes::{
|
||||
use visibility::{init_editor_visibility_on_spawn, sync_editor_visibility};
|
||||
|
||||
use crate::{
|
||||
inspector_component_active, ColliderDesc, EditorVisibility, InspectorOrder, LevelObject,
|
||||
MaterialDesc, MaterialOverride, Primitive, StaticMeshRenderer, COMPONENT_COLLIDER_DESC,
|
||||
COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_PRIMITIVE,
|
||||
COMPONENT_STATIC_MESH_RENDERER,
|
||||
inspector_component_active, BrushDesc, ColliderDesc, EditorVisibility, InspectorOrder,
|
||||
LevelObject, MaterialDesc, MaterialOverride, Primitive, StaticMeshRenderer,
|
||||
COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC,
|
||||
COMPONENT_PRIMITIVE, COMPONENT_STATIC_MESH_RENDERER,
|
||||
};
|
||||
|
||||
/// Registers hydration systems in deterministic order.
|
||||
@@ -46,6 +48,7 @@ impl Plugin for HydrationPlugin {
|
||||
Update,
|
||||
(
|
||||
hydrate_primitives,
|
||||
hydrate_brushes,
|
||||
hydrate_materials,
|
||||
hydrate_lights,
|
||||
reconcile_missing_runtime_lights,
|
||||
@@ -83,6 +86,45 @@ pub fn flush_level_object_hydration(world: &mut World) {
|
||||
.map(|(entity, desc, _)| (entity, desc.clone()))
|
||||
.collect();
|
||||
|
||||
let brush_entities_for_cleanup: Vec<Entity> = world
|
||||
.query_filtered::<(Entity, &BrushDesc), With<LevelObject>>()
|
||||
.iter(world)
|
||||
.map(|(entity, _)| entity)
|
||||
.collect();
|
||||
|
||||
let brush_targets: Vec<(
|
||||
Entity,
|
||||
BrushDesc,
|
||||
Option<MaterialDesc>,
|
||||
Option<ColliderDesc>,
|
||||
Option<InspectorOrder>,
|
||||
)> = world
|
||||
.query_filtered::<(
|
||||
Entity,
|
||||
&BrushDesc,
|
||||
Option<&MaterialDesc>,
|
||||
Option<&ColliderDesc>,
|
||||
Option<&InspectorOrder>,
|
||||
), With<LevelObject>>()
|
||||
.iter(world)
|
||||
.map(|(entity, brush, material, collider, order)| {
|
||||
(
|
||||
entity,
|
||||
brush.clone(),
|
||||
material
|
||||
.filter(|_| inspector_component_active(order, COMPONENT_MATERIAL_DESC))
|
||||
.cloned(),
|
||||
collider
|
||||
.filter(|_| inspector_component_active(order, COMPONENT_COLLIDER_DESC))
|
||||
.cloned(),
|
||||
order.cloned(),
|
||||
)
|
||||
})
|
||||
.filter(|(_, _, _, _, order)| {
|
||||
inspector_component_active(order.as_ref(), COMPONENT_BRUSH_DESC)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let static_mesh_entities_for_cleanup: Vec<Entity> = world
|
||||
.query_filtered::<(Entity, &StaticMeshRenderer), With<LevelObject>>()
|
||||
.iter(world)
|
||||
@@ -138,6 +180,17 @@ pub fn flush_level_object_hydration(world: &mut World) {
|
||||
}
|
||||
}
|
||||
|
||||
let mut generated_brush_meshes = Vec::new();
|
||||
for entity in &brush_entities_for_cleanup {
|
||||
if let Some(children) = world.get::<Children>(*entity) {
|
||||
for child in children.iter() {
|
||||
if world.get::<HydratedBrushMesh>(child).is_some() {
|
||||
generated_brush_meshes.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let visibility_targets: Vec<(Entity, EditorVisibility)> = world
|
||||
.query_filtered::<(Entity, &EditorVisibility), With<LevelObject>>()
|
||||
.iter(world)
|
||||
@@ -187,6 +240,23 @@ pub fn flush_level_object_hydration(world: &mut World) {
|
||||
commands.entity(entity).insert(MeshMaterial3d(material));
|
||||
}
|
||||
|
||||
for child in generated_brush_meshes {
|
||||
commands.entity(child).despawn();
|
||||
}
|
||||
|
||||
for (entity, brush, material, collider, _) in &brush_targets {
|
||||
spawn_brush_mesh(
|
||||
&mut commands,
|
||||
&asset_server,
|
||||
&mut meshes,
|
||||
&mut materials,
|
||||
*entity,
|
||||
brush,
|
||||
material.as_ref(),
|
||||
collider.as_ref(),
|
||||
);
|
||||
}
|
||||
|
||||
for child in generated_static_mesh_parts {
|
||||
commands.entity(child).despawn();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user