Ship production navigation authoring workflow
This commit is contained in:
1 parent
0798aa5d57
commit
b4aa61e394
35 files changed
+3898
-602
No files matched your search
@@ -63,7 +63,7 @@ impl From<&SurfaceExtension> for SurfaceExtensionKey {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Asset, AsBindGroup, Reflect, Debug, Clone)]
|
||||
#[derive(Asset, AsBindGroup, Reflect, Debug, Clone, Default)]
|
||||
#[bind_group_data(SurfaceExtensionKey)]
|
||||
pub struct SurfaceExtension {
|
||||
#[uniform(100)]
|
||||
@@ -96,23 +96,6 @@ pub struct SurfaceExtension {
|
||||
pub shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
impl Default for SurfaceExtension {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
uniform: SurfaceUniform::default(),
|
||||
texture0: None,
|
||||
texture1: None,
|
||||
texture2: None,
|
||||
texture3: None,
|
||||
texture4: None,
|
||||
texture5: None,
|
||||
texture6: None,
|
||||
texture7: None,
|
||||
shader: Handle::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SurfaceExtension {
|
||||
pub fn set_texture(&mut self, index: usize, handle: Option<Handle<Image>>) {
|
||||
match index {
|
||||
@@ -170,8 +153,8 @@ pub struct SurfaceMaterialCache {
|
||||
}
|
||||
|
||||
enum BuiltRendererMaterial {
|
||||
Standard(StandardMaterial),
|
||||
Surface(SurfaceMaterial),
|
||||
Standard(Box<StandardMaterial>),
|
||||
Surface(Box<SurfaceMaterial>),
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Debug, Clone)]
|
||||
@@ -203,7 +186,7 @@ impl Plugin for SurfaceMaterialPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
|
||||
fn sync_surface_material_bindings(
|
||||
mut commands: Commands,
|
||||
asset_server: Res<AssetServer>,
|
||||
@@ -267,6 +250,7 @@ fn sync_surface_material_bindings(
|
||||
&mut evaluator_registry,
|
||||
) {
|
||||
Ok(BuiltRendererMaterial::Surface(material)) => {
|
||||
let material = *material;
|
||||
cache.standard_only.remove(reference);
|
||||
cache.standard_handles.remove(reference);
|
||||
cache.failed_revisions.remove(reference);
|
||||
@@ -282,6 +266,7 @@ fn sync_surface_material_bindings(
|
||||
}
|
||||
}
|
||||
Ok(BuiltRendererMaterial::Standard(material)) => {
|
||||
let material = *material;
|
||||
// Plain Material assets stay on Bevy's StandardMaterial path, while still
|
||||
// sharing one live-updated handle across every renderer slot.
|
||||
let handle = standard_handle
|
||||
@@ -404,7 +389,7 @@ fn build_surface_material(
|
||||
(!asset.render_state.double_sided).then_some(bevy::render::render_resource::Face::Back);
|
||||
|
||||
let Some(evaluator) = evaluator_source.as_deref() else {
|
||||
return Ok(BuiltRendererMaterial::Standard(base));
|
||||
return Ok(BuiltRendererMaterial::Standard(Box::new(base)));
|
||||
};
|
||||
validate_surface_evaluator(evaluator)?;
|
||||
let runtime_shader_id = stable_shader_id(reference);
|
||||
@@ -443,10 +428,10 @@ fn build_surface_material(
|
||||
asset_server,
|
||||
)?;
|
||||
}
|
||||
Ok(BuiltRendererMaterial::Surface(ExtendedMaterial {
|
||||
Ok(BuiltRendererMaterial::Surface(Box::new(ExtendedMaterial {
|
||||
base,
|
||||
extension,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
|
||||
fn material_dependency_paths(path: &str) -> Result<Vec<String>, String> {
|
||||
|
||||
@@ -319,6 +319,7 @@ pub fn clear_level_objects(world: &mut World) {
|
||||
}
|
||||
|
||||
pub fn spawn_with_history(world: &mut World, mut snapshot: EditorEntitySnapshot) -> Entity {
|
||||
assign_missing_actor_ids(&mut snapshot);
|
||||
snapshot.hierarchy_sibling_index = next_sibling_index(world, None);
|
||||
let entity = spawn_snapshot(world, &snapshot);
|
||||
push_history(
|
||||
@@ -340,6 +341,9 @@ pub fn spawn_many_with_history(
|
||||
if snapshots.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
for snapshot in &mut snapshots {
|
||||
assign_missing_actor_ids(snapshot);
|
||||
}
|
||||
for (sibling_index, snapshot) in (next_sibling_index(world, None)..).zip(snapshots.iter_mut()) {
|
||||
snapshot.hierarchy_sibling_index = sibling_index;
|
||||
}
|
||||
@@ -421,12 +425,37 @@ pub fn duplicate_entities_with_history(world: &mut World, entities: &[Entity]) {
|
||||
}
|
||||
|
||||
fn assign_fresh_actor_ids(snapshot: &mut EditorEntitySnapshot) {
|
||||
snapshot.actor_id = Some(new_actor_id());
|
||||
let actor_id = new_actor_id();
|
||||
if let Some(bounds) = &mut snapshot.navigation_bounds {
|
||||
bounds.artifact_path = shared::navigation_artifact_path_for_actor(&actor_id.0);
|
||||
}
|
||||
snapshot.actor_id = Some(actor_id);
|
||||
for child in &mut snapshot.children {
|
||||
assign_fresh_actor_ids(child);
|
||||
}
|
||||
}
|
||||
|
||||
fn assign_missing_actor_ids(snapshot: &mut EditorEntitySnapshot) {
|
||||
let existing_actor_id = snapshot
|
||||
.actor_id
|
||||
.clone()
|
||||
.filter(|id| !id.0.trim().is_empty());
|
||||
let assigned_new_id = existing_actor_id.is_none();
|
||||
let actor_id = existing_actor_id.unwrap_or_else(new_actor_id);
|
||||
if let Some(bounds) = &mut snapshot.navigation_bounds {
|
||||
if assigned_new_id
|
||||
|| bounds.artifact_path == NavigationBounds::default().artifact_path
|
||||
|| shared::navigation_generated_artifact_path(&bounds.artifact_path).is_err()
|
||||
{
|
||||
bounds.artifact_path = shared::navigation_artifact_path_for_actor(&actor_id.0);
|
||||
}
|
||||
}
|
||||
snapshot.actor_id = Some(actor_id);
|
||||
for child in &mut snapshot.children {
|
||||
assign_missing_actor_ids(child);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rename_entity_with_history(world: &mut World, entity: Entity, new_name: String) {
|
||||
if !is_mutable_level_object(world, entity) {
|
||||
return;
|
||||
@@ -2825,8 +2854,10 @@ mod tests {
|
||||
#[test]
|
||||
fn snapshots_preserve_component_order_and_independent_active_state() {
|
||||
let mut world = World::new();
|
||||
let mut order = InspectorOrder::default();
|
||||
order.component_ids = vec![shared::AUTHORING_COMPONENT_LIGHT.to_string()];
|
||||
let order = InspectorOrder {
|
||||
component_ids: vec![shared::AUTHORING_COMPONENT_LIGHT.to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let mut states = AuthoringComponentStates::default();
|
||||
states.set_component_active(shared::COMPONENT_LIGHT_DESC, false);
|
||||
let entity = world
|
||||
@@ -3516,6 +3547,73 @@ mod tests {
|
||||
assert_eq!(unique.len(), ids.len(), "duplicated actors need fresh IDs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_navigation_bounds_gets_actor_owned_artifact_path() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<SelectedEntity>();
|
||||
let original_id = ActorId::new("navigation-bounds-original");
|
||||
let original_bounds = NavigationBounds::for_actor(&original_id.0);
|
||||
let original = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorKind::Navigation,
|
||||
original_id,
|
||||
Transform::IDENTITY,
|
||||
original_bounds.clone(),
|
||||
))
|
||||
.id();
|
||||
|
||||
duplicate_entities_with_history(&mut world, &[original]);
|
||||
|
||||
let (duplicate_id, duplicate_bounds) = world
|
||||
.query::<(Entity, &ActorId, &NavigationBounds)>()
|
||||
.iter(&world)
|
||||
.find_map(|(entity, actor_id, bounds)| {
|
||||
(entity != original).then_some((actor_id.clone(), bounds.clone()))
|
||||
})
|
||||
.expect("duplicated navigation bounds should exist");
|
||||
assert_ne!(
|
||||
duplicate_bounds.artifact_path,
|
||||
original_bounds.artifact_path
|
||||
);
|
||||
assert_eq!(
|
||||
duplicate_bounds.artifact_path,
|
||||
shared::navigation_artifact_path_for_actor(&duplicate_id.0)
|
||||
);
|
||||
|
||||
apply_command_undo(&mut world);
|
||||
apply_command_redo(&mut world);
|
||||
let redone = world
|
||||
.query::<(&ActorId, &NavigationBounds)>()
|
||||
.iter(&world)
|
||||
.find(|(actor_id, _)| **actor_id == duplicate_id)
|
||||
.expect("redo should preserve the duplicate actor identity");
|
||||
assert_eq!(redone.1, &duplicate_bounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_navigation_snapshot_keeps_deliberate_generated_path() {
|
||||
let mut world = World::new();
|
||||
let mut bounds = NavigationBounds::for_actor("bounds-existing");
|
||||
bounds.artifact_path = "assets/navigation/generated/custom-zone.nav.ron".into();
|
||||
let entity = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorKind::Navigation,
|
||||
ActorId::new("bounds-existing"),
|
||||
Transform::IDENTITY,
|
||||
bounds.clone(),
|
||||
))
|
||||
.id();
|
||||
let mut snapshot = snapshot_entity(&world, entity).unwrap();
|
||||
|
||||
assign_missing_actor_ids(&mut snapshot);
|
||||
|
||||
assert_eq!(snapshot.navigation_bounds.as_ref(), Some(&bounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_members_reject_direct_history_mutations() {
|
||||
let mut world = World::new();
|
||||
|
||||
@@ -88,6 +88,7 @@ pub struct SceneIo {
|
||||
pub events: VecDeque<SceneIoEvent>,
|
||||
pub tabs: Vec<SceneTab>,
|
||||
pub active_tab: usize,
|
||||
change_revision: u64,
|
||||
next_event_id: u64,
|
||||
next_tab_id: u64,
|
||||
}
|
||||
@@ -127,6 +128,7 @@ impl Default for SceneIo {
|
||||
recovery_snapshot: None,
|
||||
}],
|
||||
active_tab: 0,
|
||||
change_revision: 0,
|
||||
next_event_id: 1,
|
||||
next_tab_id: 2,
|
||||
}
|
||||
@@ -136,14 +138,20 @@ impl Default for SceneIo {
|
||||
impl SceneIo {
|
||||
pub fn mark_dirty(&mut self) {
|
||||
self.dirty = true;
|
||||
self.change_revision = self.change_revision.wrapping_add(1);
|
||||
self.sync_active_tab_metadata();
|
||||
}
|
||||
|
||||
pub fn mark_clean(&mut self) {
|
||||
self.dirty = false;
|
||||
self.change_revision = self.change_revision.wrapping_add(1);
|
||||
self.sync_active_tab_metadata();
|
||||
}
|
||||
|
||||
pub fn change_revision(&self) -> u64 {
|
||||
self.change_revision
|
||||
}
|
||||
|
||||
pub fn active_path_label(&self) -> String {
|
||||
self.active_path
|
||||
.as_ref()
|
||||
@@ -935,7 +943,7 @@ fn save_level(world: &mut World, path: &Path) -> Result<usize, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_active_scene(world: &mut World) -> Result<String, String> {
|
||||
pub(crate) fn serialize_active_scene(world: &mut World) -> Result<String, String> {
|
||||
let entities = authored_scene_entities(world);
|
||||
if world
|
||||
.resource::<SceneIo>()
|
||||
@@ -1950,11 +1958,13 @@ mod tests {
|
||||
let mut io = SceneIo::default();
|
||||
assert_eq!(io.tabs.len(), 1);
|
||||
assert!(!io.tabs[0].dirty);
|
||||
let initial_revision = io.change_revision();
|
||||
|
||||
io.active_path = Some(PathBuf::from("assets/levels/arena.scn.ron"));
|
||||
io.mark_dirty();
|
||||
|
||||
assert!(io.has_unsaved_tabs());
|
||||
assert!(io.change_revision() > initial_revision);
|
||||
assert!(io.tabs[0].dirty);
|
||||
assert_eq!(
|
||||
io.tabs[0].path.as_deref(),
|
||||
|
||||
@@ -9,9 +9,9 @@ use egui_phosphor_icons::{icons, Icon};
|
||||
use shared::{
|
||||
authoring_component_active,
|
||||
brush_math::{validate_brush, BrushDiagnosticSeverity},
|
||||
infer_actor_kind, ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc,
|
||||
AuthoringComponentStates, AuthoringLightKind, AuthoringRigidBody, BrushDesc, BrushKind,
|
||||
ColliderDesc, ColliderShapeDesc, ColorDesc, ComponentInstanceId, EditorAssetRef,
|
||||
infer_actor_kind, ActorId, ActorKind, AnimationControllerDesc, AudioListenerDesc,
|
||||
AudioSourceDesc, AuthoringComponentStates, AuthoringLightKind, AuthoringRigidBody, BrushDesc,
|
||||
BrushKind, ColliderDesc, ColliderShapeDesc, ColorDesc, ComponentInstanceId, EditorAssetRef,
|
||||
InspectorOrder, LevelObject, LightDesc, MaterialDesc, MaterialParameter,
|
||||
MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds,
|
||||
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
|
||||
@@ -690,9 +690,13 @@ fn paste_component(world: &mut World, entity: Entity, type_name: &str) {
|
||||
Some(CopiedComponent::PrefabInstance(value)) if type_name == COMPONENT_PREFAB_INSTANCE => {
|
||||
insert_direct_component(world, entity, value);
|
||||
}
|
||||
Some(CopiedComponent::NavigationBounds(value))
|
||||
Some(CopiedComponent::NavigationBounds(mut value))
|
||||
if type_name == COMPONENT_NAVIGATION_BOUNDS =>
|
||||
{
|
||||
value.artifact_path = world
|
||||
.get::<NavigationBounds>(entity)
|
||||
.map(|bounds| bounds.artifact_path.clone())
|
||||
.unwrap_or_else(|| navigation_bounds_for_entity(world, entity).artifact_path);
|
||||
crate::history::set_navigation_with_history(
|
||||
world,
|
||||
entity,
|
||||
@@ -760,6 +764,19 @@ fn reset_component(world: &mut World, entity: Entity, type_name: &str) {
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
} else if type_path == COMPONENT_NAVIGATION_BOUNDS {
|
||||
let bounds = reset_navigation_bounds_for_entity(world, entity);
|
||||
let _ = crate::history::reflected_component_transaction(
|
||||
world,
|
||||
entity,
|
||||
"Reset Component",
|
||||
component_id,
|
||||
type_path,
|
||||
move |world, entity| {
|
||||
world.entity_mut(entity).insert(bounds);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
} else {
|
||||
let _ = crate::history::reflected_component_transaction(
|
||||
world,
|
||||
@@ -809,7 +826,7 @@ fn reset_component(world: &mut World, entity: Entity, type_name: &str) {
|
||||
world,
|
||||
entity,
|
||||
crate::history::NavigationComponentState {
|
||||
bounds: Some(NavigationBounds::default()),
|
||||
bounds: Some(reset_navigation_bounds_for_entity(world, entity)),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
@@ -1609,6 +1626,19 @@ fn insert_registered_component(world: &mut World, entity: Entity, type_name: &st
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
} else if descriptor.type_name == COMPONENT_NAVIGATION_BOUNDS {
|
||||
let bounds = navigation_bounds_for_entity(world, entity);
|
||||
let _ = crate::history::reflected_component_transaction(
|
||||
world,
|
||||
entity,
|
||||
"Add Component",
|
||||
descriptor.id,
|
||||
descriptor.type_name,
|
||||
move |world, entity| {
|
||||
world.entity_mut(entity).insert(bounds);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
} else {
|
||||
let _ = crate::history::reflected_component_transaction(
|
||||
world,
|
||||
@@ -1689,9 +1719,8 @@ fn insert_registered_component(world: &mut World, entity: Entity, type_name: &st
|
||||
});
|
||||
}),
|
||||
COMPONENT_NAVIGATION_BOUNDS => insert_component(world, entity, |world, e| {
|
||||
world
|
||||
.entity_mut(e)
|
||||
.insert((ActorKind::Navigation, NavigationBounds::default()));
|
||||
let bounds = navigation_bounds_for_entity(world, e);
|
||||
world.entity_mut(e).insert((ActorKind::Navigation, bounds));
|
||||
}),
|
||||
COMPONENT_NAVIGATION_OBSTACLE => insert_component(world, entity, |world, e| {
|
||||
world
|
||||
@@ -1717,6 +1746,21 @@ fn insert_registered_component(world: &mut World, entity: Entity, type_name: &st
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_bounds_for_entity(world: &World, entity: Entity) -> NavigationBounds {
|
||||
world
|
||||
.get::<ActorId>(entity)
|
||||
.map(|actor_id| NavigationBounds::for_actor(&actor_id.0))
|
||||
.unwrap_or_else(|| NavigationBounds::for_actor(&uuid::Uuid::new_v4().to_string()))
|
||||
}
|
||||
|
||||
fn reset_navigation_bounds_for_entity(world: &World, entity: Entity) -> NavigationBounds {
|
||||
let mut bounds = navigation_bounds_for_entity(world, entity);
|
||||
if let Some(current) = world.get::<NavigationBounds>(entity) {
|
||||
bounds.artifact_path.clone_from(¤t.artifact_path);
|
||||
}
|
||||
bounds
|
||||
}
|
||||
|
||||
fn insert_component(world: &mut World, entity: Entity, insert: impl FnOnce(&mut World, Entity)) {
|
||||
let before = crate::history::snapshot_entity(world, entity);
|
||||
let old_kind = before.as_ref().map(|s| s.actor_kind);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -154,33 +154,45 @@ fn draw_navigation_visualizers(
|
||||
links: Query<(&NavigationLink, &GlobalTransform), With<LevelObject>>,
|
||||
) {
|
||||
for (value, global) in &bounds {
|
||||
let (_, rotation, center) = global.to_scale_rotation_translation();
|
||||
let half_extents = crate::ui::navigation_inspector::world_aabb_half_extents(
|
||||
global.affine(),
|
||||
value.half_extents,
|
||||
);
|
||||
let center = global.translation();
|
||||
draw_box(
|
||||
&mut gizmos,
|
||||
center,
|
||||
rotation,
|
||||
value.half_extents,
|
||||
Quat::IDENTITY,
|
||||
half_extents,
|
||||
Color::srgba(0.12, 0.82, 0.78, 0.72),
|
||||
);
|
||||
}
|
||||
for (value, global) in &obstacles {
|
||||
let (_, rotation, center) = global.to_scale_rotation_translation();
|
||||
let half_extents = crate::ui::navigation_inspector::world_aabb_half_extents(
|
||||
global.affine(),
|
||||
value.half_extents,
|
||||
);
|
||||
let center = global.translation();
|
||||
draw_box(
|
||||
&mut gizmos,
|
||||
center,
|
||||
rotation,
|
||||
value.half_extents,
|
||||
Quat::IDENTITY,
|
||||
half_extents,
|
||||
Color::srgba(1.0, 0.28, 0.22, 0.78),
|
||||
);
|
||||
}
|
||||
for (value, global) in &areas {
|
||||
let (_, rotation, center) = global.to_scale_rotation_translation();
|
||||
let half_extents = crate::ui::navigation_inspector::world_aabb_half_extents(
|
||||
global.affine(),
|
||||
value.half_extents,
|
||||
);
|
||||
let center = global.translation();
|
||||
let color = if value.walkable {
|
||||
Color::srgba(0.32, 0.72, 1.0, 0.62)
|
||||
} else {
|
||||
Color::srgba(1.0, 0.55, 0.18, 0.72)
|
||||
};
|
||||
draw_box(&mut gizmos, center, rotation, value.half_extents, color);
|
||||
draw_box(&mut gizmos, center, Quat::IDENTITY, half_extents, color);
|
||||
}
|
||||
for (value, global) in &links {
|
||||
let start = global.transform_point(value.start);
|
||||
|
||||
@@ -2,6 +2,33 @@ use bevy::prelude::*;
|
||||
use game::{launch, GamePlugin};
|
||||
|
||||
fn main() {
|
||||
let arguments = std::env::args().skip(1).collect::<Vec<_>>();
|
||||
match game::navigation::navigation_validation_argument(&arguments) {
|
||||
Ok(Some(path)) => match game::navigation::validate_navigation_artifact(&path) {
|
||||
Ok(summary) => {
|
||||
println!(
|
||||
"navigation validation passed: {} sample(s), {} link(s), {}",
|
||||
summary.enabled_sample_count,
|
||||
summary.enabled_link_count,
|
||||
summary.artifact_path.display()
|
||||
);
|
||||
return;
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"navigation validation failed for {}:\n{error}",
|
||||
path.display()
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
},
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
eprintln!("{error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
App::new()
|
||||
.add_plugins(launch::default_plugins("Bevy FPS Foundation"))
|
||||
.add_plugins(GamePlugin)
|
||||
|
||||
+181
-144
@@ -1,172 +1,63 @@
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::prelude::Vec3;
|
||||
use nav_glam::{Vec2 as NavVec2, Vec3 as NavVec3};
|
||||
use polyanya::Mesh;
|
||||
use scene::navigation::{read_navigation_artifact, NavigationBakeArtifact, NavigationLinkInput};
|
||||
use scene::navigation::{NavigationBakeArtifact, NavigationQueryPath, NavigationQueryRuntime};
|
||||
|
||||
/// Loaded navigation artifact and its baked Polyanya acceleration data.
|
||||
/// Loaded navigation artifact and its shared Polyanya query runtime.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NavigationRuntime {
|
||||
artifact: NavigationBakeArtifact,
|
||||
mesh: Mesh,
|
||||
query: NavigationQueryRuntime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct NavigationPath {
|
||||
pub points: Vec<Vec3>,
|
||||
pub length: f32,
|
||||
pub used_link_actor_id: Option<String>,
|
||||
pub used_link_actor_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl NavigationPath {
|
||||
pub fn used_link_actor_id(&self) -> Option<&str> {
|
||||
self.used_link_actor_ids.first().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<NavigationQueryPath> for NavigationPath {
|
||||
fn from(path: NavigationQueryPath) -> Self {
|
||||
Self {
|
||||
points: path.points.into_iter().map(Vec3::from_array).collect(),
|
||||
length: path.length,
|
||||
used_link_actor_ids: path.used_link_actor_ids,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NavigationRuntime {
|
||||
pub fn from_artifact(artifact: NavigationBakeArtifact) -> Result<Self, String> {
|
||||
if artifact.mesh.layers.is_empty()
|
||||
|| artifact
|
||||
.mesh
|
||||
.layers
|
||||
.iter()
|
||||
.all(|layer| layer.polygons.is_empty())
|
||||
{
|
||||
return Err("navigation artifact contains no walkable polygons; rebake it".into());
|
||||
}
|
||||
let mesh = artifact.runtime_mesh();
|
||||
Ok(Self { artifact, mesh })
|
||||
Ok(Self {
|
||||
query: NavigationQueryRuntime::from_artifact(artifact)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> Result<Self, String> {
|
||||
Self::from_artifact(read_navigation_artifact(path)?)
|
||||
Ok(Self {
|
||||
query: NavigationQueryRuntime::load(path)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn artifact(&self) -> &NavigationBakeArtifact {
|
||||
&self.artifact
|
||||
self.query.artifact()
|
||||
}
|
||||
|
||||
pub fn query(&self, start: Vec3, end: Vec3) -> Result<NavigationPath, String> {
|
||||
if !start.is_finite() || !end.is_finite() {
|
||||
return Err("navigation query endpoints must be finite".into());
|
||||
}
|
||||
|
||||
let mut best = self.direct_path(start, end).ok().map(|path| Candidate {
|
||||
path,
|
||||
weighted_cost: 0.0,
|
||||
});
|
||||
if let Some(candidate) = best.as_mut() {
|
||||
candidate.weighted_cost = candidate.path.length;
|
||||
}
|
||||
|
||||
for link in self.artifact.links.iter().filter(|link| link.enabled) {
|
||||
self.consider_link(start, end, link, false, &mut best);
|
||||
if link.bidirectional {
|
||||
self.consider_link(start, end, link, true, &mut best);
|
||||
}
|
||||
}
|
||||
|
||||
best.map(|candidate| candidate.path).ok_or_else(|| {
|
||||
"no navigation path connects the requested endpoints; inspect islands or add a link"
|
||||
.into()
|
||||
})
|
||||
self.query
|
||||
.query(start.to_array(), end.to_array())
|
||||
.map(NavigationPath::from)
|
||||
}
|
||||
|
||||
pub fn validate_links(&self) -> Vec<String> {
|
||||
let mut findings = Vec::new();
|
||||
for link in self.artifact.links.iter().filter(|link| link.enabled) {
|
||||
for (label, endpoint) in [("start", link.start), ("end", link.end)] {
|
||||
let point = NavVec2::new(endpoint[0], endpoint[2]);
|
||||
let Some(closest) = self.mesh.get_closest_point(point) else {
|
||||
findings.push(format!(
|
||||
"navigation link {} {label} endpoint is not near a walkable polygon",
|
||||
link.actor_id
|
||||
));
|
||||
continue;
|
||||
};
|
||||
if closest.position().distance(point) > self.artifact.agent.radius * 2.0 {
|
||||
findings.push(format!(
|
||||
"navigation link {} {label} endpoint is farther than two agent radii from the mesh",
|
||||
link.actor_id
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
findings
|
||||
self.query.validate_links()
|
||||
}
|
||||
|
||||
fn consider_link(
|
||||
&self,
|
||||
start: Vec3,
|
||||
end: Vec3,
|
||||
link: &NavigationLinkInput,
|
||||
reverse: bool,
|
||||
best: &mut Option<Candidate>,
|
||||
) {
|
||||
let (entry, exit) = if reverse {
|
||||
(vec3(link.end), vec3(link.start))
|
||||
} else {
|
||||
(vec3(link.start), vec3(link.end))
|
||||
};
|
||||
let (Ok(mut first), Ok(second)) =
|
||||
(self.direct_path(start, entry), self.direct_path(exit, end))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
append_distinct(&mut first.points, entry);
|
||||
append_distinct(&mut first.points, exit);
|
||||
for point in second.points.into_iter().skip(1) {
|
||||
append_distinct(&mut first.points, point);
|
||||
}
|
||||
let link_length = entry.distance(exit);
|
||||
first.length += link_length + second.length;
|
||||
first.used_link_actor_id = Some(link.actor_id.clone());
|
||||
let weighted_cost = first.length + link_length * (link.cost - 1.0);
|
||||
if best
|
||||
.as_ref()
|
||||
.is_none_or(|candidate| weighted_cost < candidate.weighted_cost)
|
||||
{
|
||||
*best = Some(Candidate {
|
||||
path: first,
|
||||
weighted_cost,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn direct_path(&self, start: Vec3, end: Vec3) -> Result<NavigationPath, String> {
|
||||
let start2 = NavVec2::new(start.x, start.z);
|
||||
let end2 = NavVec2::new(end.x, end.z);
|
||||
let path = self.mesh.path(start2, end2).ok_or_else(|| {
|
||||
"navigation endpoints are outside the same reachable mesh island".to_string()
|
||||
})?;
|
||||
let length = path.length;
|
||||
let nav_start = NavVec3::new(start.x, start.y, start.z);
|
||||
let nav_end = NavVec3::new(end.x, end.y, end.z);
|
||||
let mut points = vec![start];
|
||||
for point in path.path_with_height(nav_start, nav_end, &self.mesh) {
|
||||
append_distinct(&mut points, Vec3::new(point.x, point.y, point.z));
|
||||
}
|
||||
append_distinct(&mut points, end);
|
||||
Ok(NavigationPath {
|
||||
points,
|
||||
length,
|
||||
used_link_actor_id: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Candidate {
|
||||
path: NavigationPath,
|
||||
weighted_cost: f32,
|
||||
}
|
||||
|
||||
fn append_distinct(points: &mut Vec<Vec3>, point: Vec3) {
|
||||
if points
|
||||
.last()
|
||||
.is_none_or(|last| last.distance_squared(point) > 1.0e-8)
|
||||
{
|
||||
points.push(point);
|
||||
}
|
||||
}
|
||||
|
||||
fn vec3(value: [f32; 3]) -> Vec3 {
|
||||
Vec3::from_array(value)
|
||||
}
|
||||
|
||||
pub fn query_navigation_path(
|
||||
@@ -177,15 +68,85 @@ pub fn query_navigation_path(
|
||||
NavigationRuntime::load(artifact_path)?.query(start, end)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NavigationValidationSummary {
|
||||
pub artifact_path: PathBuf,
|
||||
pub enabled_link_count: usize,
|
||||
pub enabled_sample_count: usize,
|
||||
}
|
||||
|
||||
pub fn validate_navigation_artifact(
|
||||
artifact_path: &Path,
|
||||
) -> Result<NavigationValidationSummary, String> {
|
||||
let runtime = NavigationQueryRuntime::load(artifact_path)?;
|
||||
let mut findings = runtime.validate_links();
|
||||
findings.extend(runtime.validate_samples());
|
||||
if !findings.is_empty() {
|
||||
return Err(findings.join("\n"));
|
||||
}
|
||||
Ok(NavigationValidationSummary {
|
||||
artifact_path: artifact_path.to_path_buf(),
|
||||
enabled_link_count: runtime
|
||||
.artifact()
|
||||
.links
|
||||
.iter()
|
||||
.filter(|link| link.enabled)
|
||||
.count(),
|
||||
enabled_sample_count: runtime
|
||||
.artifact()
|
||||
.samples
|
||||
.iter()
|
||||
.filter(|sample| sample.enabled)
|
||||
.count(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn navigation_validation_argument(args: &[String]) -> Result<Option<PathBuf>, String> {
|
||||
let Some(index) = args
|
||||
.iter()
|
||||
.position(|argument| argument == "--validate-navigation")
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if args.len() != 2 || index != 0 {
|
||||
return Err(
|
||||
"usage: game --validate-navigation <project-relative-or-absolute-artifact-path>".into(),
|
||||
);
|
||||
}
|
||||
let path = args[1].trim();
|
||||
if path.is_empty() {
|
||||
return Err("navigation validation artifact path must not be empty".into());
|
||||
}
|
||||
Ok(Some(PathBuf::from(path)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use scene::navigation::{
|
||||
bake_navigation, NavigationBakeInput, NavigationLinkInput, NavigationVolumeInput,
|
||||
bake_navigation, NavigationBakeInput, NavigationGeometryInput, NavigationLinkInput,
|
||||
NavigationVolumeInput,
|
||||
};
|
||||
use shared::NavigationAgentProfile;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn floor_geometry(
|
||||
actor_id: &str,
|
||||
min_x: f32,
|
||||
max_x: f32,
|
||||
min_z: f32,
|
||||
max_z: f32,
|
||||
y: f32,
|
||||
) -> NavigationGeometryInput {
|
||||
NavigationGeometryInput {
|
||||
actor_id: actor_id.into(),
|
||||
triangles: vec![
|
||||
[[min_x, y, min_z], [max_x, y, max_z], [max_x, y, min_z]],
|
||||
[[min_x, y, min_z], [min_x, y, max_z], [max_x, y, max_z]],
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn input() -> NavigationBakeInput {
|
||||
NavigationBakeInput {
|
||||
source_scene: "assets/levels/navigation_showcase.scn.ron".into(),
|
||||
@@ -197,7 +158,7 @@ mod tests {
|
||||
merge_region_size: 2,
|
||||
..Default::default()
|
||||
},
|
||||
geometry: Vec::new(),
|
||||
geometry: vec![floor_geometry("floor", -6.0, 6.0, -6.0, 6.0, 0.0)],
|
||||
obstacles: vec![NavigationVolumeInput {
|
||||
actor_id: "wall".into(),
|
||||
center: [0.0, 0.5, 0.0],
|
||||
@@ -205,6 +166,7 @@ mod tests {
|
||||
}],
|
||||
areas: Vec::new(),
|
||||
links: Vec::new(),
|
||||
samples: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,7 +196,65 @@ mod tests {
|
||||
let path = runtime
|
||||
.query(Vec3::new(-4.0, 0.0, 0.0), Vec3::new(4.0, 0.0, 0.0))
|
||||
.unwrap();
|
||||
assert_eq!(path.used_link_actor_id.as_deref(), Some("door-link"));
|
||||
assert_eq!(path.used_link_actor_id(), Some("door-link"));
|
||||
assert_eq!(path.used_link_actor_ids, ["door-link"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_can_traverse_multiple_explicit_links() {
|
||||
let mut input = input();
|
||||
input.geometry = vec![
|
||||
floor_geometry("island-a", -6.0, -3.0, -2.0, 2.0, 0.0),
|
||||
floor_geometry("island-b", -1.5, 1.5, -2.0, 2.0, 0.0),
|
||||
floor_geometry("island-c", 3.0, 6.0, -2.0, 2.0, 0.0),
|
||||
];
|
||||
input.obstacles.clear();
|
||||
input.links = vec![
|
||||
NavigationLinkInput {
|
||||
actor_id: "link-a-b".into(),
|
||||
start: [-3.6, 0.0, 0.0],
|
||||
end: [-1.0, 0.0, 0.0],
|
||||
bidirectional: true,
|
||||
cost: 1.0,
|
||||
enabled: true,
|
||||
},
|
||||
NavigationLinkInput {
|
||||
actor_id: "link-b-c".into(),
|
||||
start: [1.0, 0.0, 0.0],
|
||||
end: [3.6, 0.0, 0.0],
|
||||
bidirectional: true,
|
||||
cost: 1.0,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
let runtime = NavigationRuntime::from_artifact(bake_navigation(&input).unwrap()).unwrap();
|
||||
let path = runtime
|
||||
.query(Vec3::new(-5.0, 0.0, 0.0), Vec3::new(5.0, 0.0, 0.0))
|
||||
.unwrap();
|
||||
assert_eq!(path.used_link_actor_ids, ["link-a-b", "link-b-c"]);
|
||||
assert!(path.length >= 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_selects_vertically_nearest_walkable_surface() {
|
||||
let mut input = input();
|
||||
input.center = [0.0, 2.0, 0.0];
|
||||
input.half_extents = [6.0, 3.0, 6.0];
|
||||
input.geometry = vec![
|
||||
floor_geometry("lower-floor", -5.0, 5.0, -5.0, 5.0, 0.0),
|
||||
floor_geometry("upper-floor", -5.0, 5.0, -5.0, 5.0, 4.0),
|
||||
];
|
||||
input.obstacles.clear();
|
||||
let runtime = NavigationRuntime::from_artifact(bake_navigation(&input).unwrap()).unwrap();
|
||||
|
||||
let lower = runtime
|
||||
.query(Vec3::new(-3.0, 0.1, 0.0), Vec3::new(3.0, 0.1, 0.0))
|
||||
.unwrap();
|
||||
let upper = runtime
|
||||
.query(Vec3::new(-3.0, 3.9, 0.0), Vec3::new(3.0, 3.9, 0.0))
|
||||
.unwrap();
|
||||
assert!(lower.points.iter().all(|point| point.y < 1.0));
|
||||
assert!(upper.points.iter().all(|point| point.y > 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -254,4 +274,21 @@ mod tests {
|
||||
.iter()
|
||||
.any(|finding| finding.contains("bad-link start")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_cli_argument_is_strict_and_window_free() {
|
||||
assert_eq!(
|
||||
navigation_validation_argument(&[
|
||||
"--validate-navigation".into(),
|
||||
"assets/navigation/generated/main.nav.ron".into(),
|
||||
])
|
||||
.unwrap(),
|
||||
Some(PathBuf::from("assets/navigation/generated/main.nav.ron"))
|
||||
);
|
||||
assert!(navigation_validation_argument(&["--validate-navigation".into()]).is_err());
|
||||
assert_eq!(
|
||||
navigation_validation_argument(&["--project".into(), ".".into()]).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
+1649
-60
File diff suppressed because it is too large.
Load diff
@@ -15,6 +15,7 @@ use shared::{
|
||||
PostProcessVolumeDesc, PrefabInstance, PrefabRef, RendererMaterialSet, ShaderSchemaAsset,
|
||||
SkinnedMeshRenderer, StaticMeshRenderer, ANIMATION_MANIFEST_SCHEMA_VERSION,
|
||||
AUDIO_CLIP_SUB_ASSET_ID, COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_SKINNED_MESH_RENDERER,
|
||||
NAVIGATION_GENERATED_ARTIFACT_DIRECTORY,
|
||||
};
|
||||
|
||||
use crate::document::{SceneComponentBlob, SceneDocument};
|
||||
@@ -113,6 +114,8 @@ pub fn validate_project(project_root: &Path) -> ProjectValidationReport {
|
||||
);
|
||||
}
|
||||
|
||||
validate_navigation_artifact_ownership(&mut report);
|
||||
|
||||
report.dependencies.sort_by(|left, right| {
|
||||
(
|
||||
&left.owner_path,
|
||||
@@ -1456,7 +1459,11 @@ fn validate_navigation_document(
|
||||
document: &SceneDocument,
|
||||
report: &mut ProjectValidationReport,
|
||||
) {
|
||||
let jobs = match crate::navigation::navigation_bake_jobs_from_document(document, source_path) {
|
||||
let jobs = match crate::navigation::resolve_navigation_bake_jobs(
|
||||
project_root,
|
||||
&project_root.join(source_path),
|
||||
Some(document.normalized_ron()),
|
||||
) {
|
||||
Ok(jobs) => jobs,
|
||||
Err(error) => {
|
||||
report.findings.push(ProjectValidationFinding {
|
||||
@@ -1473,19 +1480,66 @@ fn validate_navigation_document(
|
||||
};
|
||||
|
||||
for job in jobs {
|
||||
let normalized_artifact_path = match shared::navigation_generated_artifact_path(
|
||||
&job.artifact_path,
|
||||
) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_outside_generated_directory",
|
||||
&job.artifact_path,
|
||||
error,
|
||||
"Assign a project-relative artifact path under assets/navigation/generated/ and rebake this bounds actor.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
report.dependencies.push(ProjectDependency {
|
||||
owner_path: source_path.to_string(),
|
||||
owner_actor_id: Some(job.input.bounds_actor_id.clone()),
|
||||
kind: "navigation_artifact".into(),
|
||||
reference: job.artifact_path.clone(),
|
||||
reference: normalized_artifact_path.clone(),
|
||||
});
|
||||
let Some(path) = resolve_reference(project_root, &job.artifact_path) else {
|
||||
let fresh_artifact = match crate::navigation::bake_navigation(&job.input) {
|
||||
Ok(artifact) => artifact,
|
||||
Err(error) => {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.bake_failed",
|
||||
&normalized_artifact_path,
|
||||
&format!("deterministic navigation bake failed: {error}"),
|
||||
"Repair the bounds, agent profile, or source geometry named by the bake error, then rebake this actor.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if fresh_artifact.diagnostics.effective_component_count > 1 {
|
||||
report.findings.push(ProjectValidationFinding {
|
||||
severity: ValidationSeverity::Warning,
|
||||
code: "navigation.isolated_regions".into(),
|
||||
source_path: source_path.into(),
|
||||
owner_actor_id: Some(job.input.bounds_actor_id.clone()),
|
||||
reference: Some(normalized_artifact_path.clone()),
|
||||
message: format!(
|
||||
"navigation bake has {} raw walkable islands and {} disconnected traversable components after valid links",
|
||||
fresh_artifact.diagnostics.island_count,
|
||||
fresh_artifact.diagnostics.effective_component_count
|
||||
),
|
||||
repair: "Add explicit Navigation Links between regions that agents must traverse, or confirm the isolation is intentional.".into(),
|
||||
});
|
||||
}
|
||||
let Some(path) = resolve_reference(project_root, &normalized_artifact_path) else {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_unsafe_path",
|
||||
&job.artifact_path,
|
||||
&normalized_artifact_path,
|
||||
"navigation artifact path escapes the project",
|
||||
"Choose an artifact path under assets/navigation/generated/.",
|
||||
);
|
||||
@@ -1497,7 +1551,7 @@ fn validate_navigation_document(
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_missing",
|
||||
&job.artifact_path,
|
||||
&normalized_artifact_path,
|
||||
"navigation bounds has no baked artifact",
|
||||
"Select the bounds actor and run Scene > Navigation > Bake Selected Bounds.",
|
||||
);
|
||||
@@ -1511,47 +1565,141 @@ fn validate_navigation_document(
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_invalid",
|
||||
&job.artifact_path,
|
||||
&normalized_artifact_path,
|
||||
&error,
|
||||
"Delete the invalid generated artifact and rebake the bounds actor.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if artifact.is_stale_for(&job.input) {
|
||||
let stale = artifact.is_stale_for(&job.input);
|
||||
if stale {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_stale",
|
||||
&job.artifact_path,
|
||||
&normalized_artifact_path,
|
||||
"navigation artifact fingerprint does not match authored navigation data",
|
||||
"Rebake navigation after the authored geometry or agent-profile change.",
|
||||
);
|
||||
}
|
||||
|
||||
let mesh = artifact.runtime_mesh();
|
||||
for link in artifact.links.iter().filter(|link| link.enabled) {
|
||||
for (label, endpoint) in [("start", link.start), ("end", link.end)] {
|
||||
let point = nav_glam::Vec2::new(endpoint[0], endpoint[2]);
|
||||
let valid = mesh.get_closest_point(point).is_some_and(|closest| {
|
||||
closest.position().distance(point) <= artifact.agent.radius * 2.0
|
||||
});
|
||||
if !valid {
|
||||
} else {
|
||||
let stored_hash = crate::navigation::navigation_artifact_content_hash(&artifact);
|
||||
let fresh_hash = crate::navigation::navigation_artifact_content_hash(&fresh_artifact);
|
||||
match (stored_hash, fresh_hash) {
|
||||
(Ok(stored_hash), Ok(fresh_hash)) if stored_hash != fresh_hash => {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&link.actor_id,
|
||||
"navigation.link_unreachable",
|
||||
&job.artifact_path,
|
||||
&format!(
|
||||
"navigation link {label} endpoint is farther than two agent radii from the baked mesh"
|
||||
),
|
||||
"Move the endpoint onto a visible navigation polygon and rebake.",
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_content_mismatch",
|
||||
&normalized_artifact_path,
|
||||
"stored navigation artifact differs from a deterministic fresh bake despite a current source fingerprint",
|
||||
"Rebake this bounds actor and commit the regenerated artifact.",
|
||||
);
|
||||
}
|
||||
(Err(error), _) | (_, Err(error)) => push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.artifact_hash_failed",
|
||||
&normalized_artifact_path,
|
||||
&error,
|
||||
"Rebake this bounds actor; if hashing still fails, repair the generated artifact serializer.",
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let runtime = match crate::navigation::NavigationQueryRuntime::from_artifact(
|
||||
fresh_artifact.clone(),
|
||||
) {
|
||||
Ok(runtime) => runtime,
|
||||
Err(error) => {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.runtime_invalid",
|
||||
&normalized_artifact_path,
|
||||
&error,
|
||||
"Repair the bake inputs and rebake this bounds actor.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for finding in runtime.validate_link_findings() {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&finding.actor_id,
|
||||
"navigation.link_unreachable",
|
||||
&normalized_artifact_path,
|
||||
&finding.message,
|
||||
"Move the endpoint onto a visible navigation polygon and rebake.",
|
||||
);
|
||||
}
|
||||
for sample in fresh_artifact
|
||||
.samples
|
||||
.iter()
|
||||
.filter(|sample| sample.enabled)
|
||||
{
|
||||
if let Err(error) = runtime.query(sample.start, sample.end) {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
source_path,
|
||||
&job.input.bounds_actor_id,
|
||||
"navigation.sample_unreachable",
|
||||
&sample.id,
|
||||
&format!("navigation validation sample `{}` failed: {error}", sample.id),
|
||||
"Move the sample endpoints onto connected visible navigation polygons, add the required links, and rebake.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_navigation_artifact_ownership(report: &mut ProjectValidationReport) {
|
||||
let mut owners_by_artifact = BTreeMap::<String, Vec<(String, String)>>::new();
|
||||
for dependency in report
|
||||
.dependencies
|
||||
.iter()
|
||||
.filter(|dependency| dependency.kind == "navigation_artifact")
|
||||
{
|
||||
let Some(actor_id) = dependency.owner_actor_id.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
owners_by_artifact
|
||||
.entry(dependency.reference.clone())
|
||||
.or_default()
|
||||
.push((dependency.owner_path.clone(), actor_id.clone()));
|
||||
}
|
||||
|
||||
for (artifact_path, owners) in owners_by_artifact {
|
||||
let owners = owners.into_iter().collect::<BTreeSet<_>>();
|
||||
if owners.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let owner_list = owners
|
||||
.iter()
|
||||
.map(|(source_path, actor_id)| format!("actor `{actor_id}` in {source_path}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
for (source_path, actor_id) in owners {
|
||||
push_navigation_finding(
|
||||
report,
|
||||
&source_path,
|
||||
&actor_id,
|
||||
"navigation.artifact_duplicate_owner",
|
||||
&artifact_path,
|
||||
&format!(
|
||||
"navigation artifact is claimed by multiple bounds actors: {owner_list}"
|
||||
),
|
||||
&format!(
|
||||
"Keep one owner; give every other bounds actor a unique path under {NAVIGATION_GENERATED_ARTIFACT_DIRECTORY} (or remove and re-add Navigation Bounds), then rebake all affected actors."
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3010,7 +3158,7 @@ mod tests {
|
||||
bounds.artifact_path = "assets/navigation/generated/main_humanoid.nav.ron".to_string();
|
||||
let bounds_ron = ron::to_string(&bounds).unwrap();
|
||||
let scene = format!(
|
||||
"(schema_version:2,resources:{{}},entities:{{1:(components:{{\"shared::components::ActorId\":(\"nav-bounds\"),\"shared::navigation::NavigationBounds\":{bounds_ron},}})}})"
|
||||
"(schema_version:2,resources:{{}},entities:{{1:(components:{{\"shared::components::ActorId\":(\"nav-bounds\"),\"shared::navigation::NavigationBounds\":{bounds_ron},}}),2:(components:{{\"shared::components::ActorId\":(\"nav-floor\"),\"shared::components::Primitive\":(shape:Box,size:(10.0,0.2,10.0)),}})}})"
|
||||
);
|
||||
std::fs::write(root.join("assets/levels/main.scn.ron"), &scene).unwrap();
|
||||
if write_artifact {
|
||||
@@ -3028,6 +3176,42 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_scene_with_artifact_path(
|
||||
bounds_actor_id: &str,
|
||||
artifact_path: &str,
|
||||
include_floor: bool,
|
||||
link_height: Option<f32>,
|
||||
) -> String {
|
||||
let mut bounds = shared::NavigationBounds::for_actor(bounds_actor_id);
|
||||
bounds.half_extents = [5.0, link_height.unwrap_or(0.0).abs() + 2.0, 5.0].into();
|
||||
bounds.agent.min_region_size = 1;
|
||||
bounds.agent.merge_region_size = 2;
|
||||
bounds.artifact_path = artifact_path.to_string();
|
||||
let bounds = ron::to_string(&bounds).unwrap();
|
||||
let mut entities = format!(
|
||||
"1:(components:{{\"shared::components::ActorId\":({bounds_actor_id:?}),\"shared::navigation::NavigationBounds\":{bounds},}})"
|
||||
);
|
||||
if include_floor {
|
||||
entities.push_str(&format!(
|
||||
",2:(components:{{\"shared::components::ActorId\":({:?}),\"shared::components::Primitive\":(shape:Box,size:(10.0,0.2,10.0)),}})",
|
||||
format!("{bounds_actor_id}-floor")
|
||||
));
|
||||
}
|
||||
if let Some(height) = link_height {
|
||||
let link = shared::NavigationLink {
|
||||
start: [-1.0, height, 0.0].into(),
|
||||
end: [1.0, height, 0.0].into(),
|
||||
..Default::default()
|
||||
};
|
||||
let link = ron::to_string(&link).unwrap();
|
||||
entities.push_str(&format!(
|
||||
",3:(components:{{\"shared::components::ActorId\":({:?}),\"shared::navigation::NavigationLink\":{link},}})",
|
||||
format!("{bounds_actor_id}-link")
|
||||
));
|
||||
}
|
||||
format!("(schema_version:2,resources:{{}},entities:{{{entities}}})")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_navigation_artifact_blocks_release_with_bounds_owner() {
|
||||
let root = fixture_root();
|
||||
@@ -3057,6 +3241,208 @@ mod tests {
|
||||
.any(|finding| finding.code == "navigation.artifact_stale"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigation_artifacts_must_stay_in_generated_directory() {
|
||||
let root = fixture_root();
|
||||
let scene = navigation_scene_with_artifact_path(
|
||||
"outside-bounds",
|
||||
"assets/navigation/manual.nav.ron",
|
||||
true,
|
||||
None,
|
||||
);
|
||||
std::fs::write(root.join("assets/levels/main.scn.ron"), scene).unwrap();
|
||||
|
||||
let report = validate_project(&root);
|
||||
let finding = report
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.code == "navigation.artifact_outside_generated_directory")
|
||||
.expect("outside artifact path should be rejected");
|
||||
assert_eq!(finding.owner_actor_id.as_deref(), Some("outside-bounds"));
|
||||
assert!(finding.repair.contains("assets/navigation/generated/"));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_navigation_artifact_owners_name_every_bounds_actor() {
|
||||
let root = fixture_root();
|
||||
let artifact_path = "assets/navigation/generated/shared.nav.ron";
|
||||
std::fs::write(
|
||||
root.join("assets/levels/main.scn.ron"),
|
||||
navigation_scene_with_artifact_path("first-bounds", artifact_path, true, None),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("assets/levels/secondary.scn.ron"),
|
||||
navigation_scene_with_artifact_path("second-bounds", artifact_path, true, None),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let report = validate_project(&root);
|
||||
let findings = report
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.code == "navigation.artifact_duplicate_owner")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(findings.len(), 2, "{:?}", report.findings);
|
||||
assert!(findings.iter().any(|finding| {
|
||||
finding.owner_actor_id.as_deref() == Some("first-bounds")
|
||||
&& finding.message.contains("second-bounds")
|
||||
}));
|
||||
assert!(findings.iter().all(|finding| {
|
||||
finding.repair.contains("unique path") && finding.repair.contains("rebake")
|
||||
}));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_bake_failures_are_attributed_to_bounds_actor() {
|
||||
let root = fixture_root();
|
||||
let scene = navigation_scene_with_artifact_path(
|
||||
"empty-bounds",
|
||||
"assets/navigation/generated/empty.nav.ron",
|
||||
false,
|
||||
None,
|
||||
);
|
||||
std::fs::write(root.join("assets/levels/main.scn.ron"), scene).unwrap();
|
||||
|
||||
let report = validate_project(&root);
|
||||
let finding = report
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.code == "navigation.bake_failed")
|
||||
.expect("empty bounds should fail a fresh validation bake");
|
||||
assert_eq!(finding.owner_actor_id.as_deref(), Some("empty-bounds"));
|
||||
assert!(finding.message.contains("no primitive or additive-brush"));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_validation_uses_endpoint_height_not_only_xz() {
|
||||
let root = fixture_root();
|
||||
let artifact_path = "assets/navigation/generated/high-link.nav.ron";
|
||||
let scene = navigation_scene_with_artifact_path(
|
||||
"high-link-bounds",
|
||||
artifact_path,
|
||||
true,
|
||||
Some(10.0),
|
||||
);
|
||||
std::fs::write(root.join("assets/levels/main.scn.ron"), &scene).unwrap();
|
||||
let document = SceneDocument::from_ron_text(&scene).unwrap();
|
||||
let job = crate::navigation::navigation_bake_jobs_from_document(
|
||||
&document,
|
||||
"assets/levels/main.scn.ron",
|
||||
)
|
||||
.unwrap()
|
||||
.pop()
|
||||
.unwrap();
|
||||
let artifact = crate::navigation::bake_navigation(&job.input).unwrap();
|
||||
crate::navigation::write_navigation_artifact(&root.join(artifact_path), &artifact).unwrap();
|
||||
|
||||
let report = validate_project(&root);
|
||||
let finding = report
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.code == "navigation.link_unreachable")
|
||||
.expect("vertically distant link should be rejected");
|
||||
assert_eq!(
|
||||
finding.owner_actor_id.as_deref(),
|
||||
Some("high-link-bounds-link")
|
||||
);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_navigation_sample_blocks_release_with_bounds_owner() {
|
||||
let root = fixture_root();
|
||||
let artifact_path = "assets/navigation/generated/sample.nav.ron";
|
||||
let mut bounds = shared::NavigationBounds::for_actor("sample-bounds");
|
||||
bounds.half_extents = [5.0, 2.0, 5.0].into();
|
||||
bounds.agent.min_region_size = 1;
|
||||
bounds.agent.merge_region_size = 2;
|
||||
bounds.artifact_path = artifact_path.into();
|
||||
bounds
|
||||
.validation_samples
|
||||
.push(shared::NavigationPathSample {
|
||||
id: "outside-mesh".into(),
|
||||
start: [100.0, 0.0, 100.0].into(),
|
||||
end: [101.0, 0.0, 100.0].into(),
|
||||
enabled: true,
|
||||
});
|
||||
let bounds = ron::to_string(&bounds).unwrap();
|
||||
let scene = format!(
|
||||
r#"(schema_version:2,resources:{{}},entities:{{
|
||||
1:(components:{{"shared::components::ActorId":("sample-bounds"),"shared::navigation::NavigationBounds":{bounds},}}),
|
||||
2:(components:{{"shared::components::ActorId":("sample-floor"),"shared::components::Primitive":(shape:Box,size:(10.0,0.2,10.0)),}}),
|
||||
}})"#
|
||||
);
|
||||
std::fs::write(root.join("assets/levels/main.scn.ron"), &scene).unwrap();
|
||||
let document = SceneDocument::from_ron_text(&scene).unwrap();
|
||||
let job = crate::navigation::navigation_bake_jobs_from_document(
|
||||
&document,
|
||||
"assets/levels/main.scn.ron",
|
||||
)
|
||||
.unwrap()
|
||||
.pop()
|
||||
.unwrap();
|
||||
let artifact = crate::navigation::bake_navigation(&job.input).unwrap();
|
||||
crate::navigation::write_navigation_artifact(&root.join(artifact_path), &artifact).unwrap();
|
||||
|
||||
let report = validate_project(&root);
|
||||
let finding = report
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.code == "navigation.sample_unreachable")
|
||||
.expect("unreachable sample should block release");
|
||||
assert_eq!(finding.owner_actor_id.as_deref(), Some("sample-bounds"));
|
||||
assert_eq!(finding.reference.as_deref(), Some("outside-mesh"));
|
||||
assert_eq!(finding.severity, ValidationSeverity::Error);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnected_navigation_islands_emit_owner_warning() {
|
||||
let root = fixture_root();
|
||||
let artifact_path = "assets/navigation/generated/islands.nav.ron";
|
||||
let mut bounds = shared::NavigationBounds::for_actor("island-bounds");
|
||||
bounds.half_extents = [6.0, 2.0, 5.0].into();
|
||||
bounds.agent.min_region_size = 1;
|
||||
bounds.agent.merge_region_size = 2;
|
||||
bounds.artifact_path = artifact_path.into();
|
||||
let bounds = ron::to_string(&bounds).unwrap();
|
||||
let scene = format!(
|
||||
r#"(schema_version:2,resources:{{}},entities:{{
|
||||
1:(components:{{"shared::components::ActorId":("island-bounds"),"shared::navigation::NavigationBounds":{bounds},}}),
|
||||
2:(components:{{"shared::components::ActorId":("left-floor"),"bevy_transform::components::transform::Transform":(translation:(-3.5,0.0,0.0),rotation:(0.0,0.0,0.0,1.0),scale:(1.0,1.0,1.0)),"shared::components::Primitive":(shape:Box,size:(4.0,0.2,8.0)),}}),
|
||||
3:(components:{{"shared::components::ActorId":("right-floor"),"bevy_transform::components::transform::Transform":(translation:(3.5,0.0,0.0),rotation:(0.0,0.0,0.0,1.0),scale:(1.0,1.0,1.0)),"shared::components::Primitive":(shape:Box,size:(4.0,0.2,8.0)),}}),
|
||||
}})"#
|
||||
);
|
||||
std::fs::write(root.join("assets/levels/main.scn.ron"), &scene).unwrap();
|
||||
let document = SceneDocument::from_ron_text(&scene).unwrap();
|
||||
let job = crate::navigation::navigation_bake_jobs_from_document(
|
||||
&document,
|
||||
"assets/levels/main.scn.ron",
|
||||
)
|
||||
.unwrap()
|
||||
.pop()
|
||||
.unwrap();
|
||||
let artifact = crate::navigation::bake_navigation(&job.input).unwrap();
|
||||
assert!(artifact.diagnostics.effective_component_count > 1);
|
||||
crate::navigation::write_navigation_artifact(&root.join(artifact_path), &artifact).unwrap();
|
||||
|
||||
let report = validate_project(&root);
|
||||
let finding = report
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.code == "navigation.isolated_regions")
|
||||
.expect("multiple islands should produce an authoring warning");
|
||||
assert_eq!(finding.severity, ValidationSeverity::Warning);
|
||||
assert_eq!(finding.owner_actor_id.as_deref(), Some("island-bounds"));
|
||||
assert!(finding.message.contains("2 disconnected"));
|
||||
assert!(finding.repair.contains("Navigation Links"));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_animation_controller_collects_stable_artifact_dependencies() {
|
||||
let root = fixture_root();
|
||||
|
||||
@@ -8,6 +8,7 @@ description = "Shared reflectable authoring types and scene hydration for the FP
|
||||
[dependencies]
|
||||
avian3d.workspace = true
|
||||
bevy.workspace = true
|
||||
blake3 = "1"
|
||||
ron = "0.8"
|
||||
serde.workspace = true
|
||||
settings.workspace = true
|
||||
@@ -321,10 +321,26 @@ fn validate_navigation_actor(entity: EntityRef<'_>) -> Result<(), ActorValidatio
|
||||
.agent
|
||||
.validate()
|
||||
.map_err(|error| ActorValidationError::InvalidNavigation(error.into()))?;
|
||||
if bounds.artifact_path.trim().is_empty() {
|
||||
return Err(ActorValidationError::InvalidNavigation(
|
||||
"navigation artifact path must not be empty".into(),
|
||||
));
|
||||
crate::navigation_generated_artifact_path(&bounds.artifact_path)
|
||||
.map_err(|error| ActorValidationError::InvalidNavigation(error.into()))?;
|
||||
let mut sample_ids = HashSet::new();
|
||||
for sample in &bounds.validation_samples {
|
||||
let sample_id = sample.id.trim();
|
||||
if sample_id.is_empty() {
|
||||
return Err(ActorValidationError::InvalidNavigation(
|
||||
"navigation validation sample ID must not be empty".into(),
|
||||
));
|
||||
}
|
||||
if !sample_ids.insert(sample_id) {
|
||||
return Err(ActorValidationError::InvalidNavigation(format!(
|
||||
"navigation validation sample ID `{sample_id}` must be unique within its bounds"
|
||||
)));
|
||||
}
|
||||
if !sample.start.is_finite() || !sample.end.is_finite() || sample.start == sample.end {
|
||||
return Err(ActorValidationError::InvalidNavigation(format!(
|
||||
"navigation validation sample `{sample_id}` endpoints must be finite and distinct"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(obstacle) = entity.get::<NavigationObstacle>() {
|
||||
@@ -832,4 +848,37 @@ mod tests {
|
||||
Err(ActorValidationError::AnimationControllerUnknownDefaultState)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigation_bounds_validate_generated_path_and_unique_samples() {
|
||||
let mut world = World::new();
|
||||
let mut bounds = NavigationBounds::for_actor("bounds-main");
|
||||
bounds.validation_samples.push(crate::NavigationPathSample {
|
||||
id: "entry-to-exit".into(),
|
||||
start: Vec3::new(-2.0, 0.0, 0.0),
|
||||
end: Vec3::new(2.0, 0.0, 0.0),
|
||||
enabled: true,
|
||||
});
|
||||
let entity = level_entity(&mut world, (ActorKind::Navigation, bounds.clone()));
|
||||
assert!(validate_actor(world.entity(entity)).is_ok());
|
||||
|
||||
bounds
|
||||
.validation_samples
|
||||
.push(bounds.validation_samples[0].clone());
|
||||
world.entity_mut(entity).insert(bounds.clone());
|
||||
assert!(matches!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::InvalidNavigation(message))
|
||||
if message.contains("must be unique")
|
||||
));
|
||||
|
||||
bounds.validation_samples.pop();
|
||||
bounds.artifact_path = "assets/navigation/manual.nav.ron".into();
|
||||
world.entity_mut(entity).insert(bounds);
|
||||
assert!(matches!(
|
||||
validate_actor(world.entity(entity)),
|
||||
Err(ActorValidationError::InvalidNavigation(message))
|
||||
if message.contains("assets/navigation/generated/")
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -615,8 +615,8 @@ pub enum PrimitiveShape {
|
||||
}
|
||||
|
||||
/// Reflectable authoring primitive. Hydration turns this into `Mesh3d`.
|
||||
#[derive(Component, Reflect, Debug, Clone, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
|
||||
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Primitive {
|
||||
pub shape: PrimitiveShape,
|
||||
pub size: Vec3,
|
||||
|
||||
@@ -147,23 +147,20 @@ pub fn flush_level_object_hydration(world: &mut World) {
|
||||
Option<&InspectorOrder>,
|
||||
), With<LevelObject>>()
|
||||
.iter(world)
|
||||
.filter_map(|(entity, brush, material, collider, states, order)| {
|
||||
authoring_component_active(states, order, COMPONENT_BRUSH_DESC).then(|| {
|
||||
(
|
||||
entity,
|
||||
brush.clone(),
|
||||
material
|
||||
.filter(|_| {
|
||||
authoring_component_active(states, order, COMPONENT_MATERIAL_DESC)
|
||||
})
|
||||
.cloned(),
|
||||
collider
|
||||
.filter(|_| {
|
||||
authoring_component_active(states, order, COMPONENT_COLLIDER_DESC)
|
||||
})
|
||||
.cloned(),
|
||||
)
|
||||
})
|
||||
.filter(|(_, _, _, _, states, order)| {
|
||||
authoring_component_active(*states, *order, COMPONENT_BRUSH_DESC)
|
||||
})
|
||||
.map(|(entity, brush, material, collider, states, order)| {
|
||||
(
|
||||
entity,
|
||||
brush.clone(),
|
||||
material
|
||||
.filter(|_| authoring_component_active(states, order, COMPONENT_MATERIAL_DESC))
|
||||
.cloned(),
|
||||
collider
|
||||
.filter(|_| authoring_component_active(states, order, COMPONENT_COLLIDER_DESC))
|
||||
.cloned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -190,34 +187,25 @@ pub fn flush_level_object_hydration(world: &mut World) {
|
||||
Option<&InspectorOrder>,
|
||||
), With<LevelObject>>()
|
||||
.iter(world)
|
||||
.filter_map(
|
||||
.filter(|(_, _, _, _, _, states, order)| {
|
||||
authoring_component_active(*states, *order, COMPONENT_STATIC_MESH_RENDERER)
|
||||
})
|
||||
.map(
|
||||
|(entity, renderer, material, material_override, collider, states, order)| {
|
||||
authoring_component_active(states, order, COMPONENT_STATIC_MESH_RENDERER).then(
|
||||
|| {
|
||||
(
|
||||
entity,
|
||||
renderer.clone(),
|
||||
material
|
||||
.filter(|_| {
|
||||
authoring_component_active(
|
||||
states,
|
||||
order,
|
||||
COMPONENT_MATERIAL_DESC,
|
||||
)
|
||||
})
|
||||
.cloned(),
|
||||
material_override.cloned(),
|
||||
collider
|
||||
.filter(|_| {
|
||||
authoring_component_active(
|
||||
states,
|
||||
order,
|
||||
COMPONENT_COLLIDER_DESC,
|
||||
)
|
||||
})
|
||||
.cloned(),
|
||||
)
|
||||
},
|
||||
(
|
||||
entity,
|
||||
renderer.clone(),
|
||||
material
|
||||
.filter(|_| {
|
||||
authoring_component_active(states, order, COMPONENT_MATERIAL_DESC)
|
||||
})
|
||||
.cloned(),
|
||||
material_override.cloned(),
|
||||
collider
|
||||
.filter(|_| {
|
||||
authoring_component_active(states, order, COMPONENT_COLLIDER_DESC)
|
||||
})
|
||||
.cloned(),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -361,6 +361,7 @@ pub fn despawn_static_mesh_parts(
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn material_for_entry(
|
||||
asset_server: &AssetServer,
|
||||
materials: &mut Assets<StandardMaterial>,
|
||||
|
||||
@@ -32,9 +32,10 @@ pub use material_asset::{
|
||||
pub use navigation::*;
|
||||
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
|
||||
pub use prefab_overrides::{
|
||||
apply_prefab_overrides_on_ready, decode_prefab_overrides, encode_prefab_overrides,
|
||||
PrefabActorPath, PrefabComponentOverride, PrefabOverrides, PrefabPropertyOverride,
|
||||
PrefabStructuralOverride, PREFAB_OVERRIDE_FORMAT_VERSION,
|
||||
apply_prefab_overrides_on_ready, apply_serialized_navigation_property_override,
|
||||
decode_prefab_overrides, encode_prefab_overrides, PrefabActorPath, PrefabComponentOverride,
|
||||
PrefabOverrides, PrefabPropertyOverride, PrefabStructuralOverride,
|
||||
PREFAB_OVERRIDE_FORMAT_VERSION,
|
||||
};
|
||||
pub use renderer_material::*;
|
||||
pub use rendering_profile_asset::RenderingProfileAsset;
|
||||
@@ -94,6 +95,7 @@ impl Plugin for SharedTypesPlugin {
|
||||
.register_type::<AnimationStateDesc>()
|
||||
.register_type::<AnimationControllerDesc>()
|
||||
.register_type::<NavigationAgentProfile>()
|
||||
.register_type::<NavigationPathSample>()
|
||||
.register_type::<NavigationBounds>()
|
||||
.register_type::<NavigationObstacle>()
|
||||
.register_type::<NavigationArea>()
|
||||
@@ -149,6 +151,7 @@ impl Plugin for SharedTypesPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn migrate_legacy_authoring_component_states(
|
||||
mut commands: Commands,
|
||||
mut legacy: Query<
|
||||
|
||||
@@ -191,6 +191,15 @@ pub struct ShaderSchemaAsset {
|
||||
pub default_textures: Vec<MaterialTextureBinding>,
|
||||
}
|
||||
|
||||
impl ShaderSchemaAsset {
|
||||
pub fn load_from_path(catalog_path: &str) -> Result<Self, String> {
|
||||
let text = std::fs::read_to_string(catalog_path)
|
||||
.map_err(|err| format!("could not read {catalog_path}: {err}"))?;
|
||||
ron::from_str(&text)
|
||||
.map_err(|err| format!("invalid shader schema RON in {catalog_path}: {err}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -262,12 +271,3 @@ mod tests {
|
||||
.any(|value| value.name == "edge_width"));
|
||||
}
|
||||
}
|
||||
|
||||
impl ShaderSchemaAsset {
|
||||
pub fn load_from_path(catalog_path: &str) -> Result<Self, String> {
|
||||
let text = std::fs::read_to_string(catalog_path)
|
||||
.map_err(|err| format!("could not read {catalog_path}: {err}"))?;
|
||||
ron::from_str(&text)
|
||||
.map_err(|err| format!("invalid shader schema RON in {catalog_path}: {err}"))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const NAVIGATION_GENERATED_ARTIFACT_DIRECTORY: &str = "assets/navigation/generated/";
|
||||
pub const COMPONENT_NAVIGATION_BOUNDS: &str = "shared::navigation::NavigationBounds";
|
||||
pub const COMPONENT_NAVIGATION_OBSTACLE: &str = "shared::navigation::NavigationObstacle";
|
||||
pub const COMPONENT_NAVIGATION_AREA: &str = "shared::navigation::NavigationArea";
|
||||
@@ -54,11 +55,24 @@ impl NavigationAgentProfile {
|
||||
if !self.max_slope_deg.is_finite() || !(0.0..90.0).contains(&self.max_slope_deg) {
|
||||
return Err("maximum slope must be finite and in [0, 90) degrees");
|
||||
}
|
||||
if !self.cell_size_fraction.is_finite() || self.cell_size_fraction <= 0.0 {
|
||||
return Err("cell size fraction must be finite and greater than zero");
|
||||
if !self.cell_size_fraction.is_finite() || !(1.0..=32.0).contains(&self.cell_size_fraction)
|
||||
{
|
||||
return Err("cell size fraction must be finite and in [1, 32]");
|
||||
}
|
||||
if !self.cell_height_fraction.is_finite() || self.cell_height_fraction <= 0.0 {
|
||||
return Err("cell height fraction must be finite and greater than zero");
|
||||
if !self.cell_height_fraction.is_finite()
|
||||
|| !(1.0..=64.0).contains(&self.cell_height_fraction)
|
||||
{
|
||||
return Err("cell height fraction must be finite and in [1, 64]");
|
||||
}
|
||||
let cell_height = self.radius / self.cell_height_fraction;
|
||||
if (self.height / cell_height).ceil() > f32::from(u16::MAX) {
|
||||
return Err("agent height requires more than 65535 vertical voxels");
|
||||
}
|
||||
if (self.max_climb / cell_height).floor() > f32::from(u16::MAX) {
|
||||
return Err("maximum climb requires more than 65535 vertical voxels");
|
||||
}
|
||||
if self.min_region_size > 255 || self.merge_region_size > 255 {
|
||||
return Err("navigation region sizes must not exceed 255 voxels");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -73,6 +87,8 @@ pub struct NavigationBounds {
|
||||
pub artifact_path: String,
|
||||
#[serde(default)]
|
||||
pub auto_bake: bool,
|
||||
#[serde(default)]
|
||||
pub validation_samples: Vec<NavigationPathSample>,
|
||||
}
|
||||
|
||||
impl Default for NavigationBounds {
|
||||
@@ -82,10 +98,111 @@ impl Default for NavigationBounds {
|
||||
agent: NavigationAgentProfile::default(),
|
||||
artifact_path: "assets/navigation/generated/main_humanoid.nav.ron".into(),
|
||||
auto_bake: false,
|
||||
validation_samples: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Named local-space start/end pair persisted for bake and packaged-runtime validation.
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NavigationPathSample {
|
||||
pub id: String,
|
||||
pub start: Vec3,
|
||||
pub end: Vec3,
|
||||
#[serde(default = "default_true")]
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for NavigationPathSample {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: "sample".into(),
|
||||
start: Vec3::new(-4.0, 0.0, 0.0),
|
||||
end: Vec3::new(4.0, 0.0, 0.0),
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NavigationBounds {
|
||||
/// Creates bounds whose generated output is owned by one stable actor.
|
||||
pub fn for_actor(actor_id: &str) -> Self {
|
||||
Self {
|
||||
artifact_path: navigation_artifact_path_for_actor(actor_id),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a readable, collision-resistant artifact path derived from a persisted actor ID.
|
||||
pub fn navigation_artifact_path_for_actor(actor_id: &str) -> String {
|
||||
let mut slug = String::with_capacity(32);
|
||||
let mut last_was_separator = false;
|
||||
for character in actor_id.trim().chars() {
|
||||
if slug.len() >= 32 {
|
||||
break;
|
||||
}
|
||||
let character = character.to_ascii_lowercase();
|
||||
if character.is_ascii_alphanumeric() || matches!(character, '-' | '_') {
|
||||
slug.push(character);
|
||||
last_was_separator = false;
|
||||
} else if !slug.is_empty() && !last_was_separator {
|
||||
slug.push('-');
|
||||
last_was_separator = true;
|
||||
}
|
||||
}
|
||||
while slug.ends_with('-') {
|
||||
slug.pop();
|
||||
}
|
||||
if slug.is_empty() {
|
||||
slug.push_str("actor");
|
||||
}
|
||||
|
||||
let digest = blake3::hash(actor_id.as_bytes()).to_hex();
|
||||
format!(
|
||||
"{NAVIGATION_GENERATED_ARTIFACT_DIRECTORY}{slug}-{}.nav.ron",
|
||||
&digest[..24]
|
||||
)
|
||||
}
|
||||
|
||||
/// Normalizes and validates a project-relative generated navigation artifact path.
|
||||
pub fn navigation_generated_artifact_path(path: &str) -> Result<String, &'static str> {
|
||||
let normalized = path.replace('\\', "/");
|
||||
let relative = std::path::Path::new(&normalized);
|
||||
if normalized.trim().is_empty()
|
||||
|| relative.is_absolute()
|
||||
|| relative.components().any(|component| {
|
||||
matches!(
|
||||
component,
|
||||
std::path::Component::CurDir
|
||||
| std::path::Component::ParentDir
|
||||
| std::path::Component::RootDir
|
||||
| std::path::Component::Prefix(_)
|
||||
)
|
||||
})
|
||||
{
|
||||
return Err("navigation artifacts must be project-relative files under assets/navigation/generated/");
|
||||
}
|
||||
let canonical = relative
|
||||
.components()
|
||||
.filter_map(|component| match component {
|
||||
std::path::Component::Normal(component) => component.to_str(),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
if !canonical.starts_with(NAVIGATION_GENERATED_ARTIFACT_DIRECTORY)
|
||||
|| canonical == NAVIGATION_GENERATED_ARTIFACT_DIRECTORY.trim_end_matches('/')
|
||||
|| !canonical.ends_with(".nav.ron")
|
||||
{
|
||||
return Err(
|
||||
"navigation artifacts must be .nav.ron files under assets/navigation/generated/",
|
||||
);
|
||||
}
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
/// Axis-aligned volume carved from every overlapping navigation bake.
|
||||
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -162,7 +279,10 @@ fn default_one() -> f32 {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NavigationAgentProfile;
|
||||
use super::{
|
||||
navigation_artifact_path_for_actor, navigation_generated_artifact_path,
|
||||
NavigationAgentProfile, NAVIGATION_GENERATED_ARTIFACT_DIRECTORY,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn default_agent_profile_is_valid() {
|
||||
@@ -178,4 +298,59 @@ mod tests {
|
||||
Err("agent height must be finite and greater than twice its radius")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathological_voxel_settings_are_rejected() {
|
||||
let profile = NavigationAgentProfile {
|
||||
cell_size_fraction: 1_000_000.0,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
profile.validate(),
|
||||
Err("cell size fraction must be finite and in [1, 32]")
|
||||
);
|
||||
|
||||
let profile = NavigationAgentProfile {
|
||||
merge_region_size: 256,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
profile.validate(),
|
||||
Err("navigation region sizes must not exceed 255 voxels")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_artifact_paths_are_stable_and_actor_specific() {
|
||||
let first = navigation_artifact_path_for_actor("Bounds / Main");
|
||||
assert_eq!(first, navigation_artifact_path_for_actor("Bounds / Main"));
|
||||
assert_ne!(first, navigation_artifact_path_for_actor("Bounds / Other"));
|
||||
assert!(first.starts_with(NAVIGATION_GENERATED_ARTIFACT_DIRECTORY));
|
||||
assert!(first.ends_with(".nav.ron"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_artifact_policy_rejects_escapes_and_other_directories() {
|
||||
assert_eq!(
|
||||
navigation_generated_artifact_path("assets\\navigation\\generated\\bounds.nav.ron"),
|
||||
Ok("assets/navigation/generated/bounds.nav.ron".into())
|
||||
);
|
||||
assert_eq!(
|
||||
navigation_generated_artifact_path(
|
||||
"assets/navigation/generated//nested///bounds.nav.ron"
|
||||
),
|
||||
Ok("assets/navigation/generated/nested/bounds.nav.ron".into())
|
||||
);
|
||||
assert!(navigation_generated_artifact_path("assets/navigation/bounds.nav.ron").is_err());
|
||||
assert!(
|
||||
navigation_generated_artifact_path("assets/navigation/generated/bounds.ron").is_err()
|
||||
);
|
||||
assert!(navigation_generated_artifact_path(
|
||||
"assets/navigation/generated/../bounds.nav.ron"
|
||||
)
|
||||
.is_err());
|
||||
assert!(
|
||||
navigation_generated_artifact_path(NAVIGATION_GENERATED_ARTIFACT_DIRECTORY).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use bevy::prelude::*;
|
||||
use bevy::reflect::serde::TypedReflectDeserializer;
|
||||
use bevy::reflect::{GetPath, ParsedPath, ReflectPath};
|
||||
use bevy::world_serialization::{WorldInstanceReady, WorldInstanceSpawner};
|
||||
use serde::de::DeserializeSeed;
|
||||
use serde::de::{DeserializeOwned, DeserializeSeed};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ActorId, EditorVisibility, HydratedPrefabMember, MaterialDesc, PrefabInstance};
|
||||
@@ -198,6 +198,61 @@ pub fn validate_prefab_overrides_payload(overrides: &PrefabOverrides) -> Result<
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies one reflected property path while preserving every other field in the current value.
|
||||
///
|
||||
/// Navigation baking consumes authored prefab overrides without instantiating a Bevy world. Keep
|
||||
/// its serialized merge behavior identical to the runtime override path, including enum variants.
|
||||
pub fn apply_serialized_navigation_property_override(
|
||||
component_type: &str,
|
||||
current_component_ron: &str,
|
||||
value_component_ron: &str,
|
||||
property_path: &str,
|
||||
) -> Result<String, String> {
|
||||
fn apply<T>(current: &str, value: &str, property_path: &str) -> Result<String, String>
|
||||
where
|
||||
T: Reflect + Serialize + DeserializeOwned,
|
||||
{
|
||||
let mut current = ron::from_str::<T>(current)
|
||||
.map_err(|error| format!("invalid current component value: {error}"))?;
|
||||
let value = ron::from_str::<T>(value)
|
||||
.map_err(|error| format!("invalid override component value: {error}"))?;
|
||||
let path = ParsedPath::parse(property_path)
|
||||
.map_err(|error| format!("invalid property path `{property_path}`: {error}"))?;
|
||||
let source_value = path
|
||||
.reflect_element(&value)
|
||||
.map_err(|error| format!("override value path `{property_path}` failed: {error}"))?;
|
||||
let target_value = current
|
||||
.reflect_path_mut(&path)
|
||||
.map_err(|error| format!("target property path `{property_path}` failed: {error}"))?;
|
||||
target_value
|
||||
.try_apply(source_value)
|
||||
.map_err(|error| format!("could not apply `{property_path}`: {error}"))?;
|
||||
ron::to_string(¤t)
|
||||
.map_err(|error| format!("could not encode merged component value: {error}"))
|
||||
}
|
||||
|
||||
macro_rules! apply_component {
|
||||
($ty:ty) => {
|
||||
if component_type == std::any::type_name::<$ty>() {
|
||||
return apply::<$ty>(current_component_ron, value_component_ron, property_path);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
apply_component!(Transform);
|
||||
apply_component!(crate::Primitive);
|
||||
apply_component!(crate::BrushDesc);
|
||||
apply_component!(crate::NavigationBounds);
|
||||
apply_component!(crate::NavigationObstacle);
|
||||
apply_component!(crate::NavigationArea);
|
||||
apply_component!(crate::NavigationLink);
|
||||
apply_component!(PrefabInstance);
|
||||
apply_component!(crate::PrefabRef);
|
||||
Err(format!(
|
||||
"component `{component_type}` is not supported by serialized authoring property overrides"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn encode_prefab_overrides(overrides: &PrefabOverrides) -> Result<Option<String>, String> {
|
||||
if overrides == &PrefabOverrides::default() {
|
||||
Ok(None)
|
||||
@@ -572,6 +627,26 @@ mod tests {
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialized_property_merge_preserves_unrelated_fields_and_enum_identity() {
|
||||
let current = crate::Primitive::cuboid(Vec3::new(4.0, 0.2, 6.0));
|
||||
let value = crate::Primitive {
|
||||
shape: crate::PrimitiveShape::Sphere,
|
||||
size: Vec3::splat(99.0),
|
||||
};
|
||||
let merged = apply_serialized_navigation_property_override(
|
||||
std::any::type_name::<crate::Primitive>(),
|
||||
&ron::to_string(¤t).unwrap(),
|
||||
&ron::to_string(&value).unwrap(),
|
||||
"shape",
|
||||
)
|
||||
.unwrap();
|
||||
let merged: crate::Primitive = ron::from_str(&merged).unwrap();
|
||||
|
||||
assert_eq!(merged.shape, crate::PrimitiveShape::Sphere);
|
||||
assert_eq!(merged.size, current.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_inner_override_payload_is_rejected_during_decode() {
|
||||
let mut instance = PrefabInstance::new("prefab", "assets/prefabs/test.scn.ron");
|
||||
|
||||
Reference in new issue
Block a user