Build renderer and material component foundations

Add dedicated skinned rendering, pose restoration, shared Material and Material Instance slots, registry-driven components, Surface/Solari integration, transactional schema upgrades, navigation authoring, documentation, and evaluation evidence.
This commit is contained in:
Rbanh committed 2026-07-12 00:24:06 -04:00
1 parent 0553a85220
commit 0798aa5d57
169 files changed
+27098 -3469

No files matched your search

+202 -85
View File
@@ -9,14 +9,37 @@ use bevy::prelude::*;
use crate::{
animation_clip_source_index, animation_skeleton_source_index, brush_math::validate_brush,
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
LightDesc, ModelRef, ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance,
PrefabRef, Primitive, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
AUDIO_CLIP_SUB_ASSET_ID,
};
/// One-shot deterministic kind from authoring components (scene migration only).
/// Deterministic presentation/compatibility hint derived from authoring components.
///
/// Validation is component-driven; this priority only chooses an icon/default
/// label when an actor composes several compatible behaviors (for example a
/// rendered mesh with a light).
pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
entity.get::<LevelObject>()?;
if entity.get::<PrefabRef>().is_some() || entity.get::<PrefabInstance>().is_some() {
return Some(ActorKind::PrefabAnchor);
}
if entity.get::<SkinnedMeshRenderer>().is_some() {
return Some(ActorKind::SkinnedMesh);
}
if entity.get::<BrushDesc>().is_some() {
return Some(ActorKind::Brush);
}
if entity.get::<Primitive>().is_some() || entity.get::<StaticMeshRenderer>().is_some() {
return Some(ActorKind::StaticMesh);
}
if entity.get::<ModelRef>().is_some() {
return Some(ActorKind::ImportedModel);
}
if entity.get::<LightDesc>().is_some() {
return Some(ActorKind::Light);
}
if entity.get::<PlayerSpawn>().is_some() {
return Some(ActorKind::PlayerSpawn);
}
@@ -35,27 +58,19 @@ pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
if entity.get::<ObjectiveMarker>().is_some() {
return Some(ActorKind::Objective);
}
if entity.get::<LightDesc>().is_some() {
return Some(ActorKind::Light);
}
if entity.get::<BrushDesc>().is_some() {
return Some(ActorKind::Brush);
}
if entity.get::<Primitive>().is_some() || entity.get::<StaticMeshRenderer>().is_some() {
return Some(ActorKind::StaticMesh);
}
if entity.get::<ModelRef>().is_some() {
return Some(ActorKind::ImportedModel);
}
if entity.get::<PrefabRef>().is_some() || entity.get::<PrefabInstance>().is_some() {
return Some(ActorKind::PrefabAnchor);
}
if entity.get::<AudioSourceDesc>().is_some() {
return Some(ActorKind::AudioSource);
}
if entity.get::<AudioListenerDesc>().is_some() {
return Some(ActorKind::AudioListener);
}
if entity.get::<NavigationBounds>().is_some()
|| entity.get::<NavigationObstacle>().is_some()
|| entity.get::<NavigationArea>().is_some()
|| entity.get::<NavigationLink>().is_some()
{
return Some(ActorKind::Navigation);
}
Some(ActorKind::Empty)
}
@@ -75,6 +90,13 @@ pub enum ActorValidationError {
ImportedModelMissingModelRef,
ImportedModelHasPrimitive,
ImportedModelHasStaticMeshRenderer,
SkinnedMeshMissingRenderer,
SkinnedMeshInvalidRenderer,
SkinnedMeshHasPrimitive,
SkinnedMeshHasStaticMeshRenderer,
SkinnedMeshHasModelRef,
SkinnedMeshRendererActorKindMismatch,
ConflictingGeometrySources,
LightMissingLightDesc,
LightHasPrimitive,
LightHasModelRef,
@@ -93,7 +115,7 @@ pub enum ActorValidationError {
AudioSourceMissingBus,
AudioListenerMissingDesc,
AudioListenerInvalidEarGap,
AnimationControllerMissingModelRef,
AnimationControllerMissingSkinnedMeshRenderer,
AnimationControllerMissingSkeleton,
AnimationControllerInvalidSkeletonReference,
AnimationControllerEmptyStateId,
@@ -104,6 +126,7 @@ pub enum ActorValidationError {
AnimationControllerInvalidCrossfade,
AnimationControllerMissingDefaultState,
AnimationControllerUnknownDefaultState,
InvalidNavigation(String),
}
fn is_finite_positive(v: f32) -> bool {
@@ -120,9 +143,10 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
return Ok(());
}
let Some(kind) = entity.get::<ActorKind>() else {
let Some(_stored_kind) = entity.get::<ActorKind>() else {
return Err(ActorValidationError::MissingActorKind);
};
let kind = infer_actor_kind(entity).unwrap_or(ActorKind::Empty);
if entity.get::<Transform>().is_none() {
return Err(ActorValidationError::MissingTransform);
@@ -135,13 +159,50 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
validate_audio_listener(listener)?;
}
if let Some(controller) = entity.get::<AnimationControllerDesc>() {
if entity.get::<ModelRef>().is_none() {
return Err(ActorValidationError::AnimationControllerMissingModelRef);
if entity.get::<SkinnedMeshRenderer>().is_none() {
return Err(ActorValidationError::AnimationControllerMissingSkinnedMeshRenderer);
}
validate_animation_controller(controller)?;
}
let geometry_source_count = usize::from(entity.get::<Primitive>().is_some())
+ usize::from(entity.get::<BrushDesc>().is_some())
+ usize::from(entity.get::<StaticMeshRenderer>().is_some())
+ usize::from(entity.get::<SkinnedMeshRenderer>().is_some())
+ usize::from(entity.get::<ModelRef>().is_some());
if geometry_source_count > 1 {
return Err(ActorValidationError::ConflictingGeometrySources);
}
if let Some(brush) = entity.get::<BrushDesc>() {
let report = validate_brush(brush);
if !report.is_valid() {
let message = report
.diagnostics
.into_iter()
.find(|diagnostic| {
diagnostic.severity == crate::brush_math::BrushDiagnosticSeverity::Error
})
.map(|diagnostic| diagnostic.message)
.unwrap_or_else(|| "Brush geometry is invalid.".to_string());
return Err(ActorValidationError::InvalidBrushGeometry(message));
}
}
if let Some(renderer) = entity.get::<SkinnedMeshRenderer>() {
if renderer.path.trim().is_empty() {
return Err(ActorValidationError::SkinnedMeshInvalidRenderer);
}
}
if let Some(desc) = entity.get::<PostProcessVolumeDesc>() {
validate_post_process_volume(desc)?;
}
if entity.get::<NavigationBounds>().is_some()
|| entity.get::<NavigationObstacle>().is_some()
|| entity.get::<NavigationArea>().is_some()
|| entity.get::<NavigationLink>().is_some()
{
validate_navigation_actor(entity)?;
}
match kind {
match &kind {
ActorKind::Brush => {
let Some(brush) = entity.get::<BrushDesc>() else {
return Err(ActorValidationError::BrushMissingDesc);
@@ -152,24 +213,10 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
if entity.get::<StaticMeshRenderer>().is_some() {
return Err(ActorValidationError::BrushHasStaticMeshRenderer);
}
if entity.get::<LightDesc>().is_some() {
return Err(ActorValidationError::BrushHasLight);
}
if entity.get::<ModelRef>().is_some() {
return Err(ActorValidationError::BrushHasModelRef);
}
let report = validate_brush(brush);
if !report.is_valid() {
let message = report
.diagnostics
.into_iter()
.find(|diagnostic| {
diagnostic.severity == crate::brush_math::BrushDiagnosticSeverity::Error
})
.map(|diagnostic| diagnostic.message)
.unwrap_or_else(|| "Brush geometry is invalid.".to_string());
return Err(ActorValidationError::InvalidBrushGeometry(message));
}
let _ = brush;
}
ActorKind::StaticMesh => {
let has_static_mesh_renderer = entity
@@ -178,13 +225,24 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
if entity.get::<Primitive>().is_none() && !has_static_mesh_renderer {
return Err(ActorValidationError::StaticMeshMissingPrimitive);
}
if entity.get::<LightDesc>().is_some() {
return Err(ActorValidationError::StaticMeshHasLight);
}
if entity.get::<ModelRef>().is_some() {
return Err(ActorValidationError::StaticMeshHasModelRef);
}
}
ActorKind::SkinnedMesh => {
let Some(_renderer) = entity.get::<SkinnedMeshRenderer>() else {
return Err(ActorValidationError::SkinnedMeshMissingRenderer);
};
if entity.get::<Primitive>().is_some() {
return Err(ActorValidationError::SkinnedMeshHasPrimitive);
}
if entity.get::<StaticMeshRenderer>().is_some() {
return Err(ActorValidationError::SkinnedMeshHasStaticMeshRenderer);
}
if entity.get::<ModelRef>().is_some() {
return Err(ActorValidationError::SkinnedMeshHasModelRef);
}
}
ActorKind::ImportedModel => {
if entity.get::<ModelRef>().is_none() {
return Err(ActorValidationError::ImportedModelMissingModelRef);
@@ -200,40 +258,13 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
if entity.get::<LightDesc>().is_none() {
return Err(ActorValidationError::LightMissingLightDesc);
}
if entity.get::<Primitive>().is_some() {
return Err(ActorValidationError::LightHasPrimitive);
}
if entity.get::<ModelRef>().is_some() {
return Err(ActorValidationError::LightHasModelRef);
}
if entity.get::<StaticMeshRenderer>().is_some() {
return Err(ActorValidationError::LightHasStaticMeshRenderer);
}
// Other compatible authoring components may be composed with a light.
}
ActorKind::PostProcessVolume => {
let Some(desc) = entity.get::<PostProcessVolumeDesc>() else {
return Err(ActorValidationError::PostProcessVolumeMissingDesc);
};
if !is_finite_positive(desc.half_extents.x)
|| !is_finite_positive(desc.half_extents.y)
|| !is_finite_positive(desc.half_extents.z)
{
return Err(ActorValidationError::PostProcessVolumeInvalidHalfExtents);
}
if !is_finite_non_negative(desc.blend_distance) {
return Err(ActorValidationError::PostProcessVolumeInvalidBlendDistance);
}
let o = &desc.overrides;
if let Some(v) = o.exposure_ev100 {
if !v.is_finite() {
return Err(ActorValidationError::PostProcessVolumeInvalidOverrideScalar);
}
}
if let Some(v) = o.fog_density {
if !v.is_finite() || v < 0.0 {
return Err(ActorValidationError::PostProcessVolumeInvalidOverrideScalar);
}
}
let _ = desc;
}
ActorKind::AudioSource => {
if entity.get::<AudioSourceDesc>().is_none() {
@@ -245,6 +276,7 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
return Err(ActorValidationError::AudioListenerMissingDesc);
}
}
ActorKind::Navigation => {}
ActorKind::Empty
| ActorKind::PrefabAnchor
| ActorKind::PlayerSpawn
@@ -257,6 +289,93 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
Ok(())
}
fn validate_post_process_volume(desc: &PostProcessVolumeDesc) -> Result<(), ActorValidationError> {
if !is_finite_positive(desc.half_extents.x)
|| !is_finite_positive(desc.half_extents.y)
|| !is_finite_positive(desc.half_extents.z)
{
return Err(ActorValidationError::PostProcessVolumeInvalidHalfExtents);
}
if !is_finite_non_negative(desc.blend_distance) {
return Err(ActorValidationError::PostProcessVolumeInvalidBlendDistance);
}
let overrides = &desc.overrides;
if overrides
.exposure_ev100
.is_some_and(|value| !value.is_finite())
|| overrides
.fog_density
.is_some_and(|value| !value.is_finite() || value < 0.0)
{
return Err(ActorValidationError::PostProcessVolumeInvalidOverrideScalar);
}
Ok(())
}
fn validate_navigation_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError> {
let mut component_count = 0;
if let Some(bounds) = entity.get::<NavigationBounds>() {
component_count += 1;
validate_vec3_positive(bounds.half_extents, "navigation bounds")?;
bounds
.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(),
));
}
}
if let Some(obstacle) = entity.get::<NavigationObstacle>() {
component_count += 1;
validate_vec3_positive(obstacle.half_extents, "navigation obstacle")?;
}
if let Some(area) = entity.get::<NavigationArea>() {
component_count += 1;
validate_vec3_positive(area.half_extents, "navigation area")?;
if area.id.trim().is_empty() {
return Err(ActorValidationError::InvalidNavigation(
"navigation area ID must not be empty".into(),
));
}
if !is_finite_positive(area.cost) {
return Err(ActorValidationError::InvalidNavigation(
"navigation area cost must be finite and greater than zero".into(),
));
}
}
if let Some(link) = entity.get::<NavigationLink>() {
component_count += 1;
if !link.start.is_finite() || !link.end.is_finite() || link.start == link.end {
return Err(ActorValidationError::InvalidNavigation(
"navigation link endpoints must be finite and distinct".into(),
));
}
if !is_finite_positive(link.cost) {
return Err(ActorValidationError::InvalidNavigation(
"navigation link cost must be finite and greater than zero".into(),
));
}
}
if component_count != 1 {
return Err(ActorValidationError::InvalidNavigation(
"navigation actors must own exactly one bounds, obstacle, area, or link component"
.into(),
));
}
Ok(())
}
fn validate_vec3_positive(value: Vec3, label: &str) -> Result<(), ActorValidationError> {
if !value.is_finite() || value.min_element() <= 0.0 {
return Err(ActorValidationError::InvalidNavigation(format!(
"{label} half extents must be finite and greater than zero"
)));
}
Ok(())
}
fn validate_audio_source(source: &AudioSourceDesc) -> Result<(), ActorValidationError> {
let Some(clip) = source.clip.as_ref() else {
return Err(ActorValidationError::AudioSourceMissingClip);
@@ -423,7 +542,7 @@ mod tests {
}
#[test]
fn validate_static_mesh_rejects_light() {
fn validate_static_mesh_composes_with_light_and_uses_derived_hint() {
let mut world = World::new();
let e = level_entity(
&mut world,
@@ -433,9 +552,10 @@ mod tests {
LightDesc::default(),
),
);
assert!(validate_actor(world.entity(e)).is_ok());
assert_eq!(
validate_actor(world.entity(e)),
Err(ActorValidationError::StaticMeshHasLight)
infer_actor_kind(world.entity(e)),
Some(ActorKind::StaticMesh)
);
}
@@ -459,7 +579,7 @@ mod tests {
);
assert_eq!(
validate_actor(world.entity(e)),
Err(ActorValidationError::BrushHasStaticMeshRenderer)
Err(ActorValidationError::ConflictingGeometrySources)
);
}
@@ -587,20 +707,17 @@ mod tests {
}
#[test]
fn animation_controller_requires_model_and_resolved_skeleton() {
fn animation_controller_requires_skinned_renderer_and_resolved_skeleton() {
let mut world = World::new();
let entity = level_entity(
&mut world,
(ActorKind::ImportedModel, animation_controller()),
);
let entity = level_entity(&mut world, (ActorKind::SkinnedMesh, animation_controller()));
assert_eq!(
validate_actor(world.entity(entity)),
Err(ActorValidationError::AnimationControllerMissingModelRef)
Err(ActorValidationError::AnimationControllerMissingSkinnedMeshRenderer)
);
world
.entity_mut(entity)
.insert(ModelRef::new("assets/models/animated.glb"));
.insert(SkinnedMeshRenderer::new("assets/models/animated.glb"));
let mut controller = animation_controller();
controller.skeleton = None;
world.entity_mut(entity).insert(controller);
@@ -627,8 +744,8 @@ mod tests {
let entity = level_entity(
&mut world,
(
ActorKind::ImportedModel,
ModelRef::new("assets/models/animated.glb"),
ActorKind::SkinnedMesh,
SkinnedMeshRenderer::new("assets/models/animated.glb"),
animation_controller(),
),
);
@@ -666,8 +783,8 @@ mod tests {
let entity = level_entity(
&mut world,
(
ActorKind::ImportedModel,
ModelRef::new("assets/models/animated.glb"),
ActorKind::SkinnedMesh,
SkinnedMeshRenderer::new("assets/models/animated.glb"),
animation_controller(),
),
);
+79 -2
View File
@@ -5,10 +5,11 @@ use serde::{Deserialize, Serialize};
use crate::EditorAssetRef;
pub const ANIMATION_MANIFEST_SCHEMA_VERSION: u32 = 2;
pub const ANIMATION_MANIFEST_SCHEMA_VERSION: u32 = 3;
pub const ANIMATION_ARTIFACT_DIR: &str = "assets/animations/generated";
pub const ANIMATION_CLIP_SUB_ASSET_PREFIX: &str = "animation:clip:";
pub const ANIMATION_SKELETON_SUB_ASSET_PREFIX: &str = "animation:skeleton:";
pub const COMPONENT_SKINNED_MESH_RENDERER: &str = "shared::animation::SkinnedMeshRenderer";
pub const COMPONENT_ANIMATION_CONTROLLER_DESC: &str = "shared::animation::AnimationControllerDesc";
const DEFAULT_CROSSFADE_SECONDS: f32 = 0.2;
@@ -75,6 +76,54 @@ impl AnimationSkeletonSignature {
}
}
/// Authoring renderer for rigged geometry that must retain its imported joint hierarchy.
///
/// Unlike [`crate::StaticMeshRenderer`], this component never flattens source primitives into
/// independent mesh slots. Hydration instantiates the selected model scene so Bevy can preserve
/// its `SkinnedMesh`, joint entities, inverse bind poses, and animation player bindings.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkinnedMeshRenderer {
/// Stable asset-registry UUID. Empty only for legacy or unresolved references.
#[serde(default)]
pub asset_id: String,
/// Asset path relative to `assets/`, e.g. `models/character.glb`.
pub path: String,
/// Scene index whose hierarchy owns the skinned primitives and joints.
#[serde(default)]
pub scene_index: usize,
/// Stable material slots for every draw binding in the imported animated hierarchy.
#[serde(default)]
pub materials: crate::RendererMaterialSet,
}
impl SkinnedMeshRenderer {
pub fn new(path: impl Into<String>) -> Self {
Self {
asset_id: String::new(),
path: path.into(),
scene_index: 0,
materials: crate::RendererMaterialSet::default(),
}
}
pub fn with_asset_id(mut self, asset_id: impl Into<String>) -> Self {
self.asset_id = asset_id.into();
self
}
/// Asset-server path for FBX `#SceneN` labels (see `bevy_ufbx`).
pub fn fbx_scene_asset_path(path: &str, scene_index: usize) -> String {
format!("{path}#Scene{scene_index}")
}
}
impl Default for SkinnedMeshRenderer {
fn default() -> Self {
Self::new(String::new())
}
}
/// Authored playback window inside an imported clip.
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
@@ -135,7 +184,7 @@ impl Default for AnimationStateDesc {
}
}
/// Scene-authored single-layer animation controller.
/// Scene-authored single-layer animation controller for a sibling [`SkinnedMeshRenderer`].
///
/// Bevy graph, player, transition, and instantiated-world state are derived at runtime.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -191,6 +240,12 @@ pub struct AnimationManifest {
pub schema_version: u32,
pub asset_id: String,
pub label: String,
/// Explicit imported clip shown as the asset's edit-mode rest presentation.
///
/// This is a stable clip sub-asset ID. `None` deliberately preserves the imported node pose;
/// importers and placement code must never guess the first clip.
#[serde(default)]
pub default_animation_clip_id: Option<String>,
pub source: AnimationManifestSource,
/// Whether this source format can hydrate the extracted animation data at runtime.
pub runtime_supported: bool,
@@ -315,4 +370,26 @@ mod tests {
assert_eq!(animation_skeleton_source_index(&skeleton), Some(3));
assert_eq!(animation_clip_source_index(&skeleton), None);
}
#[test]
fn schema_v2_manifest_defaults_to_imported_rest_pose() {
let legacy = r#"(
schema_version: 2,
asset_id: "model-id",
label: "Legacy",
source: (
path: "assets/models/legacy.glb",
format: "glb",
fingerprint: (byte_len: 1, modified_unix_secs: 0, content_hash: "hash"),
dependencies: [],
),
runtime_supported: true,
skeletons: [],
clips: [],
diagnostics: [],
)"#;
let manifest: AnimationManifest = ron::from_str(legacy).unwrap();
assert!(manifest.default_animation_clip_id.is_none());
}
}
+268 -20
View File
@@ -80,16 +80,39 @@ impl ComponentInstanceId {
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct InspectorOrder {
/// Stable component IDs used by current scenes.
#[serde(default)]
pub component_ids: Vec<String>,
/// Legacy reflected type paths used by schema-v3 scenes.
#[serde(default)]
pub component_type_names: Vec<String>,
/// Legacy schema-v3 storage. New authoring writes active state to
/// [`AuthoringComponentStates`]; this field remains readable so old scenes can
/// be upgraded without losing disabled components.
#[serde(default)]
pub component_states: Vec<InspectorComponentState>,
}
/// Persisted active state for authoring components.
///
/// This is intentionally separate from [`InspectorOrder`]: hydration and runtime
/// behavior must not depend on how the editor happens to arrange component cards.
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct AuthoringComponentStates {
#[serde(default)]
pub states: Vec<InspectorComponentState>,
}
/// Per-component inspector metadata that must survive scene save/load.
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct InspectorComponentState {
/// Stable authoring component identity used by current scenes.
#[serde(default)]
pub component_id: String,
/// Legacy schema-v3 reflected type path.
#[serde(default)]
pub type_name: String,
#[serde(default = "default_true")]
pub active: bool,
@@ -98,6 +121,7 @@ pub struct InspectorComponentState {
impl Default for InspectorComponentState {
fn default() -> Self {
Self {
component_id: String::new(),
type_name: String::new(),
active: true,
}
@@ -106,41 +130,64 @@ impl Default for InspectorComponentState {
impl InspectorOrder {
pub fn is_component_active(&self, type_name: &str) -> bool {
let component_id = authoring_component_key(type_name);
self.component_states
.iter()
.find(|state| state.type_name == type_name)
.find(|state| {
state.component_id == component_id
|| state.type_name == type_name
|| state.type_name == component_id
})
.map(|state| state.active)
.unwrap_or(true)
}
pub fn set_component_active(&mut self, type_name: impl Into<String>, active: bool) {
let type_name = type_name.into();
if let Some(state) = self
.component_states
.iter_mut()
.find(|state| state.type_name == type_name)
{
let component_id = authoring_component_key(&type_name).to_string();
if let Some(state) = self.component_states.iter_mut().find(|state| {
state.component_id == component_id
|| state.type_name == type_name
|| state.type_name == component_id
}) {
state.component_id = component_id;
state.type_name.clear();
state.active = active;
} else {
self.component_states
.push(InspectorComponentState { type_name, active });
self.component_states.push(InspectorComponentState {
component_id,
type_name: String::new(),
active,
});
}
}
pub fn ensure_component_order(&mut self, present: &[&str]) {
for type_name in present {
let component_id = authoring_component_key(type_name);
if !self
.component_type_names
.component_ids
.iter()
.any(|existing| existing == type_name)
.any(|existing| existing == component_id)
{
self.component_type_names.push((*type_name).to_string());
self.component_ids.push(component_id.to_string());
}
}
// Once the editor touches order, the stable-ID representation is
// authoritative and legacy paths no longer need to be re-saved.
self.component_type_names.clear();
}
pub fn ordered_components<'a>(&self, present: &[&'a str]) -> Vec<&'a str> {
let mut ordered = Vec::new();
for component_id in &self.component_ids {
if let Some(present_type) = present
.iter()
.find(|present| authoring_component_key(present) == component_id)
{
ordered.push(*present_type);
}
}
for type_name in &self.component_type_names {
if let Some(present_type) = present.iter().find(|present| **present == type_name) {
ordered.push(*present_type);
@@ -157,29 +204,186 @@ impl InspectorOrder {
pub fn move_component(&mut self, type_name: &str, offset: isize, present: &[&str]) -> bool {
self.ensure_component_order(present);
let Some(index) = self
.component_type_names
.component_ids
.iter()
.position(|existing| existing == type_name)
.position(|existing| existing == authoring_component_key(type_name))
else {
return false;
};
let target = (index as isize + offset)
.clamp(0, self.component_type_names.len() as isize - 1) as usize;
let target =
(index as isize + offset).clamp(0, self.component_ids.len() as isize - 1) as usize;
if target == index {
return false;
}
let item = self.component_type_names.remove(index);
self.component_type_names.insert(target, item);
let item = self.component_ids.remove(index);
self.component_ids.insert(target, item);
true
}
}
impl AuthoringComponentStates {
pub fn is_component_active(&self, type_name: &str) -> bool {
let component_id = authoring_component_key(type_name);
self.states
.iter()
.find(|state| {
state.component_id == component_id
|| state.type_name == type_name
|| state.type_name == component_id
})
.map(|state| state.active)
.unwrap_or(true)
}
pub fn set_component_active(&mut self, type_name: impl Into<String>, active: bool) {
let type_name = type_name.into();
let component_id = authoring_component_key(&type_name).to_string();
if let Some(state) = self.states.iter_mut().find(|state| {
state.component_id == component_id
|| state.type_name == type_name
|| state.type_name == component_id
}) {
state.component_id = component_id;
state.type_name.clear();
state.active = active;
} else {
self.states.push(InspectorComponentState {
component_id,
type_name: String::new(),
active,
});
}
}
pub fn remove_component(&mut self, type_name: &str) {
let component_id = authoring_component_key(type_name);
self.states.retain(|state| {
state.component_id != component_id
&& state.type_name != type_name
&& state.type_name != component_id
});
}
}
/// Returns whether a persisted authoring component is enabled.
///
/// `legacy_order` is consulted only when an older scene has not yet been migrated
/// to [`AuthoringComponentStates`].
pub fn authoring_component_active(
states: Option<&AuthoringComponentStates>,
legacy_order: Option<&InspectorOrder>,
type_name: &str,
) -> bool {
states
.map(|states| states.is_component_active(type_name))
.or_else(|| legacy_order.map(|order| order.is_component_active(type_name)))
.unwrap_or(true)
}
pub fn inspector_component_active(order: Option<&InspectorOrder>, type_name: &str) -> bool {
order
.map(|order| order.is_component_active(type_name))
.unwrap_or(true)
}
// Stable authoring component identities. These are editor/protocol keys; reflected
// Rust type paths remain serialization details and may change during refactors.
pub const AUTHORING_COMPONENT_PRIMITIVE: &str = "render.primitive";
pub const AUTHORING_COMPONENT_BRUSH: &str = "render.brush";
pub const AUTHORING_COMPONENT_STATIC_MESH_RENDERER: &str = "render.static_mesh_renderer";
pub const AUTHORING_COMPONENT_SKINNED_MESH_RENDERER: &str = "render.skinned_mesh_renderer";
pub const AUTHORING_COMPONENT_MATERIAL: &str = "render.material";
pub const AUTHORING_COMPONENT_LIGHT: &str = "render.light";
pub const AUTHORING_COMPONENT_ANIMATION_CONTROLLER: &str = "animation.controller";
pub const AUTHORING_COMPONENT_AUDIO_SOURCE: &str = "audio.source";
pub const AUTHORING_COMPONENT_AUDIO_LISTENER: &str = "audio.listener";
pub const AUTHORING_COMPONENT_RIGID_BODY: &str = "physics.rigid_body";
pub const AUTHORING_COMPONENT_COLLIDER: &str = "physics.collider";
pub const AUTHORING_COMPONENT_LEGACY_PHYSICS_BODY: &str = "physics.legacy_body";
pub const AUTHORING_COMPONENT_PLAYER_SPAWN: &str = "gameplay.player_spawn";
pub const AUTHORING_COMPONENT_WEAPON_SPAWN: &str = "gameplay.weapon_spawn";
pub const AUTHORING_COMPONENT_TRIGGER_VOLUME: &str = "gameplay.trigger_volume";
pub const AUTHORING_COMPONENT_TEAM_SPAWN: &str = "gameplay.team_spawn";
pub const AUTHORING_COMPONENT_OBJECTIVE: &str = "gameplay.objective";
pub const AUTHORING_COMPONENT_POST_PROCESS_VOLUME: &str = "render.post_process_volume";
pub const AUTHORING_COMPONENT_NAVIGATION_BOUNDS: &str = "navigation.bounds";
pub const AUTHORING_COMPONENT_NAVIGATION_OBSTACLE: &str = "navigation.obstacle";
pub const AUTHORING_COMPONENT_NAVIGATION_AREA: &str = "navigation.area";
pub const AUTHORING_COMPONENT_NAVIGATION_LINK: &str = "navigation.link";
/// Resolves either a stable authoring ID or a reflected Rust type path to its
/// stable editor/protocol identity. Unknown extension keys are returned as
/// `None` and remain usable as-is by generic state/order storage.
pub fn authoring_component_id(key: &str) -> Option<&'static str> {
match key {
AUTHORING_COMPONENT_PRIMITIVE | COMPONENT_PRIMITIVE => Some(AUTHORING_COMPONENT_PRIMITIVE),
AUTHORING_COMPONENT_BRUSH | COMPONENT_BRUSH_DESC => Some(AUTHORING_COMPONENT_BRUSH),
AUTHORING_COMPONENT_STATIC_MESH_RENDERER | COMPONENT_STATIC_MESH_RENDERER => {
Some(AUTHORING_COMPONENT_STATIC_MESH_RENDERER)
}
AUTHORING_COMPONENT_SKINNED_MESH_RENDERER | "shared::animation::SkinnedMeshRenderer" => {
Some(AUTHORING_COMPONENT_SKINNED_MESH_RENDERER)
}
AUTHORING_COMPONENT_MATERIAL | COMPONENT_MATERIAL_DESC => {
Some(AUTHORING_COMPONENT_MATERIAL)
}
AUTHORING_COMPONENT_LIGHT | COMPONENT_LIGHT_DESC => Some(AUTHORING_COMPONENT_LIGHT),
AUTHORING_COMPONENT_ANIMATION_CONTROLLER | "shared::animation::AnimationControllerDesc" => {
Some(AUTHORING_COMPONENT_ANIMATION_CONTROLLER)
}
AUTHORING_COMPONENT_AUDIO_SOURCE | COMPONENT_AUDIO_SOURCE_DESC => {
Some(AUTHORING_COMPONENT_AUDIO_SOURCE)
}
AUTHORING_COMPONENT_AUDIO_LISTENER | COMPONENT_AUDIO_LISTENER_DESC => {
Some(AUTHORING_COMPONENT_AUDIO_LISTENER)
}
AUTHORING_COMPONENT_RIGID_BODY | COMPONENT_RIGID_BODY_DESC => {
Some(AUTHORING_COMPONENT_RIGID_BODY)
}
AUTHORING_COMPONENT_COLLIDER | COMPONENT_COLLIDER_DESC => {
Some(AUTHORING_COMPONENT_COLLIDER)
}
AUTHORING_COMPONENT_LEGACY_PHYSICS_BODY | COMPONENT_PHYSICS_BODY => {
Some(AUTHORING_COMPONENT_LEGACY_PHYSICS_BODY)
}
AUTHORING_COMPONENT_PLAYER_SPAWN | COMPONENT_PLAYER_SPAWN => {
Some(AUTHORING_COMPONENT_PLAYER_SPAWN)
}
AUTHORING_COMPONENT_WEAPON_SPAWN | COMPONENT_WEAPON_SPAWN => {
Some(AUTHORING_COMPONENT_WEAPON_SPAWN)
}
AUTHORING_COMPONENT_TRIGGER_VOLUME | COMPONENT_TRIGGER_VOLUME => {
Some(AUTHORING_COMPONENT_TRIGGER_VOLUME)
}
AUTHORING_COMPONENT_TEAM_SPAWN | COMPONENT_TEAM_SPAWN => {
Some(AUTHORING_COMPONENT_TEAM_SPAWN)
}
AUTHORING_COMPONENT_OBJECTIVE | COMPONENT_OBJECTIVE_MARKER => {
Some(AUTHORING_COMPONENT_OBJECTIVE)
}
AUTHORING_COMPONENT_POST_PROCESS_VOLUME | COMPONENT_POST_PROCESS_VOLUME => {
Some(AUTHORING_COMPONENT_POST_PROCESS_VOLUME)
}
AUTHORING_COMPONENT_NAVIGATION_BOUNDS | "shared::navigation::NavigationBounds" => {
Some(AUTHORING_COMPONENT_NAVIGATION_BOUNDS)
}
AUTHORING_COMPONENT_NAVIGATION_OBSTACLE | "shared::navigation::NavigationObstacle" => {
Some(AUTHORING_COMPONENT_NAVIGATION_OBSTACLE)
}
AUTHORING_COMPONENT_NAVIGATION_AREA | "shared::navigation::NavigationArea" => {
Some(AUTHORING_COMPONENT_NAVIGATION_AREA)
}
AUTHORING_COMPONENT_NAVIGATION_LINK | "shared::navigation::NavigationLink" => {
Some(AUTHORING_COMPONENT_NAVIGATION_LINK)
}
_ => None,
}
}
pub fn authoring_component_key(key: &str) -> &str {
authoring_component_id(key).unwrap_or(key)
}
pub const COMPONENT_PRIMITIVE: &str = "shared::components::Primitive";
pub const COMPONENT_BRUSH_DESC: &str = "shared::components::BrushDesc";
pub const COMPONENT_STATIC_MESH_RENDERER: &str = "shared::components::StaticMeshRenderer";
@@ -700,6 +904,11 @@ pub struct MeshRenderSlot {
pub id: ComponentInstanceId,
pub name: String,
pub mesh: EditorAssetRef,
/// Stable renderer material slot used by this draw part.
#[serde(default)]
pub material_slot_id: ComponentInstanceId,
/// Legacy inline imported-material reference. Schema-v4 migration moves this into the
/// renderer's shared `RendererMaterialSet`.
#[serde(default)]
pub material: Option<EditorAssetRef>,
#[serde(default)]
@@ -718,6 +927,7 @@ impl Default for MeshRenderSlot {
id: ComponentInstanceId::default(),
name: "Mesh".into(),
mesh: EditorAssetRef::default(),
material_slot_id: ComponentInstanceId::default(),
material: None,
local_transform: Transform::default(),
visible: true,
@@ -730,6 +940,9 @@ impl Default for MeshRenderSlot {
/// Backward-compatible alias for old code paths while scenes migrate to slots.
pub type StaticMeshRendererEntry = MeshRenderSlot;
/// Public renderer-foundation name for one static draw part.
pub type StaticMeshPart = MeshRenderSlot;
/// Reflectable static mesh renderer. Hydration turns entries into child `Mesh3d`
/// entities and source/default materials.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -737,15 +950,48 @@ pub type StaticMeshRendererEntry = MeshRenderSlot;
pub struct StaticMeshRenderer {
#[serde(default, alias = "entries")]
pub slots: Vec<MeshRenderSlot>,
#[serde(default)]
pub materials: crate::RendererMaterialSet,
}
impl StaticMeshRenderer {
pub fn empty() -> Self {
Self { slots: Vec::new() }
Self {
slots: Vec::new(),
materials: crate::RendererMaterialSet::default(),
}
}
pub fn single(slot: MeshRenderSlot) -> Self {
Self { slots: vec![slot] }
pub fn single(mut slot: MeshRenderSlot) -> Self {
if slot.material_slot_id.0.trim().is_empty() {
slot.material_slot_id = ComponentInstanceId::new(format!("slot:{}", slot.id.0));
}
let source_material = slot.material.clone().map(crate::MaterialRef::new);
let materials = crate::RendererMaterialSet {
slots: vec![crate::RendererMaterialSlot {
id: slot.material_slot_id.clone(),
name: slot.name.clone(),
source_material,
material: None,
}],
orphaned_assignments: Vec::new(),
};
Self {
slots: vec![slot],
materials,
}
}
pub fn material_slot_for_part(
&self,
part: &MeshRenderSlot,
) -> Option<&crate::RendererMaterialSlot> {
let slot_id = if part.material_slot_id.0.trim().is_empty() {
&part.id
} else {
&part.material_slot_id
};
self.materials.slot(slot_id)
}
}
@@ -1147,6 +1393,7 @@ pub enum ActorKind {
Empty,
Brush,
StaticMesh,
SkinnedMesh,
ImportedModel,
Light,
PrefabAnchor,
@@ -1158,6 +1405,7 @@ pub enum ActorKind {
Objective,
AudioSource,
AudioListener,
Navigation,
}
/// Inspector upper bound for point/spot [`LightDesc::intensity`] (lumens).
+14 -7
View File
@@ -9,9 +9,10 @@ use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;
use crate::{
asset_server_path, brush_math::validate_brush, inspector_component_active, BrushDesc,
BrushFaceDesc, ColliderDesc, InspectorOrder, LevelObject, MaterialAsset, MaterialDesc,
COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
asset_server_path, authoring_component_active, brush_math::validate_brush,
AuthoringComponentStates, BrushDesc, BrushFaceDesc, ColliderDesc, InspectorOrder, LevelObject,
MaterialAsset, MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
COMPONENT_MATERIAL_DESC,
};
use super::materials::material_from_desc;
@@ -33,6 +34,7 @@ pub fn hydrate_brushes(
&BrushDesc,
Option<&MaterialDesc>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
@@ -42,6 +44,7 @@ pub fn hydrate_brushes(
Changed<BrushDesc>,
Changed<MaterialDesc>,
Changed<ColliderDesc>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
@@ -49,9 +52,9 @@ pub fn hydrate_brushes(
children: Query<&Children>,
generated_brushes: Query<(), With<HydratedBrushMesh>>,
) {
for (entity, brush, material, collider, order) in &brushes {
for (entity, brush, material, collider, states, legacy_order) in &brushes {
despawn_brush_mesh(&mut commands, entity, &children, &generated_brushes);
if !inspector_component_active(order, COMPONENT_BRUSH_DESC) {
if !authoring_component_active(states, legacy_order, COMPONENT_BRUSH_DESC) {
continue;
}
spawn_brush_mesh(
@@ -61,8 +64,12 @@ pub fn hydrate_brushes(
&mut materials,
entity,
brush,
material.filter(|_| inspector_component_active(order, COMPONENT_MATERIAL_DESC)),
collider.filter(|_| inspector_component_active(order, COMPONENT_COLLIDER_DESC)),
material.filter(|_| {
authoring_component_active(states, legacy_order, COMPONENT_MATERIAL_DESC)
}),
collider.filter(|_| {
authoring_component_active(states, legacy_order, COMPONENT_COLLIDER_DESC)
}),
);
}
}
+33 -10
View File
@@ -5,8 +5,8 @@ use bevy::prelude::*;
use settings::{ActiveCameraRenderProfile, GiPath, RenderingCapabilities, RenderingSettings};
use crate::{
inspector_component_active, AuthoringLightKind, InspectorOrder, LevelObject, LightDesc,
COMPONENT_LIGHT_DESC,
authoring_component_active, AuthoringComponentStates, AuthoringLightKind, InspectorOrder,
LevelObject, LightDesc, COMPONENT_LIGHT_DESC,
};
/// Legacy directional lux below this is treated as invalid (see ADR 0011).
@@ -31,21 +31,36 @@ pub fn hydrate_lights(
settings: Res<settings::ProjectSettings>,
profile: Option<Res<ActiveCameraRenderProfile>>,
caps: Option<Res<RenderingCapabilities>>,
lights: Query<(Entity, Ref<LightDesc>, Option<Ref<InspectorOrder>>), With<LevelObject>>,
lights: Query<
(
Entity,
Ref<LightDesc>,
Option<Ref<AuthoringComponentStates>>,
Option<Ref<InspectorOrder>>,
),
With<LevelObject>,
>,
) {
let rendering = &settings.rendering;
let render_stack_changed = profile.as_ref().is_some_and(|profile| profile.is_changed())
|| caps.as_ref().is_some_and(|caps| caps.is_changed());
let profile = profile.as_deref();
let caps = caps.as_deref();
for (entity, light, order) in &lights {
let order_changed = order.as_ref().is_some_and(|order| order.is_changed());
if !light.is_changed() && !order_changed && !render_stack_changed {
for (entity, light, states, legacy_order) in &lights {
let state_changed = states.as_ref().is_some_and(|states| states.is_changed());
let legacy_changed = legacy_order
.as_ref()
.is_some_and(|order| order.is_changed());
if !light.is_changed() && !state_changed && !legacy_changed && !render_stack_changed {
continue;
}
let mut entity_commands = commands.entity(entity);
strip_light_components(&mut entity_commands);
if !inspector_component_active(order.as_deref(), COMPONENT_LIGHT_DESC) {
if !authoring_component_active(
states.as_deref(),
legacy_order.as_deref(),
COMPONENT_LIGHT_DESC,
) {
continue;
}
if local_light_disabled_in_solari(&light, profile, caps) {
@@ -86,7 +101,15 @@ pub fn reconcile_missing_runtime_lights(
settings: Res<settings::ProjectSettings>,
profile: Option<Res<ActiveCameraRenderProfile>>,
caps: Option<Res<RenderingCapabilities>>,
lights: Query<(Entity, &LightDesc, Option<&InspectorOrder>), With<LevelObject>>,
lights: Query<
(
Entity,
&LightDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
With<LevelObject>,
>,
points: Query<(), With<PointLight>>,
spots: Query<(), With<SpotLight>>,
directionals: Query<(), With<DirectionalLight>>,
@@ -94,8 +117,8 @@ pub fn reconcile_missing_runtime_lights(
let rendering = &settings.rendering;
let profile = profile.as_deref();
let caps = caps.as_deref();
for (entity, light, order) in &lights {
if !inspector_component_active(order, COMPONENT_LIGHT_DESC) {
for (entity, light, states, legacy_order) in &lights {
if !authoring_component_active(states, legacy_order, COMPONENT_LIGHT_DESC) {
continue;
}
if local_light_disabled_in_solari(light, profile, caps) {
+11 -5
View File
@@ -3,8 +3,8 @@
use bevy::prelude::*;
use crate::{
asset_server_path, inspector_component_active, InspectorOrder, LevelObject, MaterialDesc,
MaterialShaderKind, Primitive, COMPONENT_MATERIAL_DESC,
asset_server_path, authoring_component_active, AuthoringComponentStates, InspectorOrder,
LevelObject, MaterialDesc, MaterialShaderKind, Primitive, COMPONENT_MATERIAL_DESC,
};
#[allow(clippy::type_complexity)]
@@ -13,7 +13,12 @@ pub fn hydrate_materials(
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
targets: Query<
(Entity, &MaterialDesc, Option<&InspectorOrder>),
(
Entity,
&MaterialDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
With<LevelObject>,
With<Mesh3d>,
@@ -21,13 +26,14 @@ pub fn hydrate_materials(
Changed<MaterialDesc>,
Added<Mesh3d>,
Changed<Primitive>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
) {
for (entity, desc, order) in &targets {
if !inspector_component_active(order, COMPONENT_MATERIAL_DESC) {
for (entity, desc, states, legacy_order) in &targets {
if !authoring_component_active(states, legacy_order, COMPONENT_MATERIAL_DESC) {
commands
.entity(entity)
.remove::<MeshMaterial3d<StandardMaterial>>();
+92 -49
View File
@@ -7,6 +7,7 @@ mod models;
mod physics;
mod prefabs;
mod primitives;
mod skinned_meshes;
mod static_meshes;
pub mod strip;
mod visibility;
@@ -27,6 +28,11 @@ use physics::hydrate_physics;
use prefabs::{hydrate_prefabs, tag_hydrated_prefab_members};
pub use prefabs::{HydratedPrefabMember, HydratedPrefabReady, PrefabHydrationBlocked};
use primitives::{hydrate_primitives, primitive_mesh};
pub use skinned_meshes::HydratedSkinnedMeshRoot;
use skinned_meshes::{
apply_skinned_renderer_material_changes, cleanup_removed_skinned_mesh_renderers,
hydrate_skinned_mesh_renderers, mark_skinned_materials_ready,
};
use static_meshes::{
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
StaticMeshArtifactCache,
@@ -37,10 +43,10 @@ use visibility::{
};
use crate::{
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,
authoring_component_active, AuthoringComponentStates, 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.
@@ -50,6 +56,7 @@ impl Plugin for HydrationPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<StaticMeshArtifactCache>()
.add_observer(tag_hydrated_prefab_members)
.add_observer(mark_skinned_materials_ready)
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
.add_systems(
Update,
@@ -60,6 +67,9 @@ impl Plugin for HydrationPlugin {
hydrate_lights,
reconcile_missing_runtime_lights,
hydrate_static_mesh_renderers,
hydrate_skinned_mesh_renderers,
apply_skinned_renderer_material_changes,
cleanup_removed_skinned_mesh_renderers,
hydrate_models,
hydrate_prefabs,
hydrate_physics,
@@ -89,17 +99,31 @@ pub fn flush_level_object_hydration(world: &mut World) {
}
let primitives: Vec<(Entity, Primitive)> = world
.query_filtered::<(Entity, &Primitive, Option<&InspectorOrder>), With<LevelObject>>()
.query_filtered::<(
Entity,
&Primitive,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<LevelObject>>()
.iter(world)
.filter(|(_, _, order)| inspector_component_active(*order, COMPONENT_PRIMITIVE))
.map(|(entity, primitive, _)| (entity, primitive.clone()))
.filter(|(_, _, states, order)| {
authoring_component_active(*states, *order, COMPONENT_PRIMITIVE)
})
.map(|(entity, primitive, _, _)| (entity, primitive.clone()))
.collect();
let material_targets: Vec<(Entity, MaterialDesc)> = world
.query_filtered::<(Entity, &MaterialDesc, Option<&InspectorOrder>), With<LevelObject>>()
.query_filtered::<(
Entity,
&MaterialDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<LevelObject>>()
.iter(world)
.filter(|(_, _, order)| inspector_component_active(*order, COMPONENT_MATERIAL_DESC))
.map(|(entity, desc, _)| (entity, desc.clone()))
.filter(|(_, _, states, order)| {
authoring_component_active(*states, *order, COMPONENT_MATERIAL_DESC)
})
.map(|(entity, desc, _, _)| (entity, desc.clone()))
.collect();
let brush_entities_for_cleanup: Vec<Entity> = world
@@ -113,31 +137,33 @@ pub fn flush_level_object_hydration(world: &mut World) {
BrushDesc,
Option<MaterialDesc>,
Option<ColliderDesc>,
Option<InspectorOrder>,
)> = world
.query_filtered::<(
Entity,
&BrushDesc,
Option<&MaterialDesc>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
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)
.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(),
)
})
})
.collect();
@@ -153,7 +179,6 @@ pub fn flush_level_object_hydration(world: &mut World) {
Option<MaterialDesc>,
Option<MaterialOverride>,
Option<ColliderDesc>,
Option<InspectorOrder>,
)> = world
.query_filtered::<(
Entity,
@@ -161,28 +186,41 @@ pub fn flush_level_object_hydration(world: &mut World) {
Option<&MaterialDesc>,
Option<&MaterialOverride>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<LevelObject>>()
.iter(world)
.map(
|(entity, renderer, material, material_override, collider, order)| {
(
entity,
renderer.clone(),
material
.filter(|_| inspector_component_active(order, COMPONENT_MATERIAL_DESC))
.cloned(),
material_override.cloned(),
collider
.filter(|_| inspector_component_active(order, COMPONENT_COLLIDER_DESC))
.cloned(),
order.cloned(),
.filter_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(),
)
},
)
},
)
.filter(|(_, _, _, _, _, order)| {
inspector_component_active(order.as_ref(), COMPONENT_STATIC_MESH_RENDERER)
})
.collect();
let mut generated_static_mesh_parts = Vec::new();
@@ -225,13 +263,18 @@ pub fn flush_level_object_hydration(world: &mut World) {
.cloned();
let lights: Vec<(Entity, crate::LightDesc)> = world
.query_filtered::<(Entity, &crate::LightDesc, Option<&InspectorOrder>), With<LevelObject>>()
.query_filtered::<(
Entity,
&crate::LightDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<LevelObject>>()
.iter(world)
.filter(|(_, light, order)| {
inspector_component_active(*order, COMPONENT_LIGHT_DESC)
.filter(|(_, light, states, order)| {
authoring_component_active(*states, *order, COMPONENT_LIGHT_DESC)
&& !lights::local_light_disabled_in_solari(light, profile.as_ref(), caps.as_ref())
})
.map(|(entity, light, _)| (entity, light.clone()))
.map(|(entity, light, _, _)| (entity, light.clone()))
.collect();
let mut state: SystemState<(
@@ -261,7 +304,7 @@ pub fn flush_level_object_hydration(world: &mut World) {
commands.entity(child).despawn();
}
for (entity, brush, material, collider, _) in &brush_targets {
for (entity, brush, material, collider) in &brush_targets {
spawn_brush_mesh(
&mut commands,
&asset_server,
@@ -278,7 +321,7 @@ pub fn flush_level_object_hydration(world: &mut World) {
commands.entity(child).despawn();
}
for (entity, renderer, material, material_override, collider, _) in &static_mesh_renderers {
for (entity, renderer, material, material_override, collider) in &static_mesh_renderers {
spawn_static_mesh_parts(
&mut commands,
&asset_server,
+28 -12
View File
@@ -4,23 +4,37 @@ use avian3d::prelude::*;
use bevy::prelude::*;
use crate::{
inspector_component_active, AuthoringRigidBody, ColliderDesc, ColliderShapeDesc,
InspectorOrder, LevelObject, PhysicsBody, RigidBodyDesc, COMPONENT_COLLIDER_DESC,
COMPONENT_PHYSICS_BODY, COMPONENT_RIGID_BODY_DESC,
authoring_component_active, AuthoringComponentStates, AuthoringRigidBody, ColliderDesc,
ColliderShapeDesc, InspectorOrder, LevelObject, PhysicsBody, RigidBodyDesc,
COMPONENT_COLLIDER_DESC, COMPONENT_PHYSICS_BODY, COMPONENT_RIGID_BODY_DESC,
};
#[allow(clippy::type_complexity)]
pub fn hydrate_physics(
mut commands: Commands,
physics: Query<
(Entity, &PhysicsBody, Option<&InspectorOrder>),
(
Entity,
&PhysicsBody,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
With<LevelObject>,
Or<(Changed<PhysicsBody>, Changed<InspectorOrder>)>,
Or<(
Changed<PhysicsBody>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
new_physics: Query<
(Entity, &PhysicsBody, Option<&InspectorOrder>),
(
Entity,
&PhysicsBody,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(With<LevelObject>, Added<PhysicsBody>),
>,
split_physics: Query<
@@ -28,6 +42,7 @@ pub fn hydrate_physics(
Entity,
Option<&RigidBodyDesc>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
@@ -37,13 +52,14 @@ pub fn hydrate_physics(
Added<RigidBodyDesc>,
Changed<ColliderDesc>,
Added<ColliderDesc>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
) {
for (entity, body, order) in new_physics.iter().chain(physics.iter()) {
if !inspector_component_active(order, COMPONENT_PHYSICS_BODY) {
for (entity, body, states, legacy_order) in new_physics.iter().chain(physics.iter()) {
if !authoring_component_active(states, legacy_order, COMPONENT_PHYSICS_BODY) {
commands
.entity(entity)
.remove::<RigidBody>()
@@ -63,12 +79,12 @@ pub fn hydrate_physics(
.insert((rigid_body, body.collider.clone()));
}
for (entity, rigid_body, collider, order) in &split_physics {
for (entity, rigid_body, collider, states, legacy_order) in &split_physics {
let mut entity_commands = commands.entity(entity);
entity_commands.remove::<RigidBody>().remove::<Collider>();
if let Some(rigid_body) =
rigid_body.filter(|_| inspector_component_active(order, COMPONENT_RIGID_BODY_DESC))
if let Some(rigid_body) = rigid_body
.filter(|_| authoring_component_active(states, legacy_order, COMPONENT_RIGID_BODY_DESC))
{
entity_commands.insert(rigid_body_from_desc(rigid_body.body));
}
@@ -76,7 +92,7 @@ pub fn hydrate_physics(
let Some(collider) = collider else {
continue;
};
if !inspector_component_active(order, COMPONENT_COLLIDER_DESC) {
if !authoring_component_active(states, legacy_order, COMPONENT_COLLIDER_DESC) {
continue;
}
if !collider.enabled || matches!(collider.shape, ColliderShapeDesc::StaticMesh { .. }) {
+11 -5
View File
@@ -3,8 +3,8 @@
use bevy::prelude::*;
use crate::{
inspector_component_active, InspectorOrder, LevelObject, Primitive, PrimitiveShape,
COMPONENT_PRIMITIVE,
authoring_component_active, AuthoringComponentStates, InspectorOrder, LevelObject, Primitive,
PrimitiveShape, COMPONENT_PRIMITIVE,
};
pub(crate) fn primitive_mesh(primitive: &Primitive) -> Mesh {
@@ -32,20 +32,26 @@ pub(crate) fn primitive_mesh(primitive: &Primitive) -> Mesh {
pub fn hydrate_primitives(
mut commands: Commands,
primitives: Query<
(Entity, &Primitive, Option<&InspectorOrder>),
(
Entity,
&Primitive,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
With<LevelObject>,
Or<(
Added<Primitive>,
Changed<Primitive>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
mut meshes: ResMut<Assets<Mesh>>,
) {
for (entity, primitive, order) in &primitives {
if !inspector_component_active(order, COMPONENT_PRIMITIVE) {
for (entity, primitive, states, legacy_order) in &primitives {
if !authoring_component_active(states, legacy_order, COMPONENT_PRIMITIVE) {
commands
.entity(entity)
.remove::<Mesh3d>()
@@ -0,0 +1,473 @@
//! Dedicated scene hydration for rigged and skinned model geometry.
use std::fs;
use bevy::gltf::GltfAssetLabel;
use bevy::prelude::WorldAssetRoot;
use bevy::prelude::*;
use bevy::world_serialization::WorldInstanceReady;
use serde::Deserialize;
use crate::{
asset_server_path, authoring_component_active, AuthoringComponentStates,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, SkinnedMeshRenderer,
ANIMATION_ARTIFACT_DIR, COMPONENT_SKINNED_MESH_RENDERER,
};
use super::static_meshes::{
renderer_error_material, resolve_renderer_material_handle, StaticMeshArtifactCache,
};
/// Runtime hierarchy root generated for one authored [`SkinnedMeshRenderer`].
///
/// The loaded world contains Bevy's actual skinned-mesh bindings and joints. Keeping this marker
/// distinct from `HydratedModelRoot` prevents animation systems from binding to generic imported
/// scene instances.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
pub struct HydratedSkinnedMeshRoot {
pub owner: Entity,
}
#[derive(Component, Debug, Clone, PartialEq, Eq)]
pub(super) struct HydratedSkinnedMeshSource {
asset_id: String,
path: String,
scene_index: usize,
}
impl From<&SkinnedMeshRenderer> for HydratedSkinnedMeshSource {
fn from(renderer: &SkinnedMeshRenderer) -> Self {
Self {
asset_id: renderer.asset_id.clone(),
path: renderer.path.clone(),
scene_index: renderer.scene_index,
}
}
}
#[derive(Component, Default)]
pub(super) struct SkinnedMaterialsDirty;
#[derive(Deserialize)]
struct AnimationArtifactLookup {
source: AnimationSourceLookup,
}
#[derive(Deserialize)]
struct AnimationSourceLookup {
path: String,
}
pub fn skinned_mesh_manifest_path(asset_id: &str) -> String {
format!("{ANIMATION_ARTIFACT_DIR}/{asset_id}.animation.ron")
}
/// Resolves the current model source from the animation artifact rather than the static-mesh
/// artifact. The authored cached path remains the fallback when a legacy/unindexed asset has no
/// generated animation metadata.
pub fn skinned_mesh_source_path(asset_id: &str) -> Result<String, String> {
let path = skinned_mesh_manifest_path(asset_id);
let text = fs::read_to_string(&path)
.map_err(|error| format!("could not read skinned mesh artifact {path}: {error}"))?;
let artifact: AnimationArtifactLookup = ron::from_str(&text)
.map_err(|error| format!("could not parse skinned mesh artifact {path}: {error}"))?;
Ok(artifact.source.path)
}
#[allow(clippy::type_complexity)]
pub(super) fn hydrate_skinned_mesh_renderers(
mut commands: Commands,
asset_server: Res<AssetServer>,
renderers: Query<
(
Entity,
&SkinnedMeshRenderer,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
With<LevelObject>,
Or<(
Added<SkinnedMeshRenderer>,
Changed<SkinnedMeshRenderer>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
generated_roots: Query<(
Entity,
&HydratedSkinnedMeshRoot,
Option<&HydratedSkinnedMeshSource>,
)>,
) {
for (entity, renderer, states, legacy_order) in &renderers {
if !authoring_component_active(states, legacy_order, COMPONENT_SKINNED_MESH_RENDERER) {
for (root, generated, _) in &generated_roots {
if generated.owner == entity {
commands.entity(root).despawn();
}
}
continue;
}
let requested_source = HydratedSkinnedMeshSource::from(renderer);
let mut matching_root = None;
for (root, generated, source) in &generated_roots {
if generated.owner == entity {
if source == Some(&requested_source) {
matching_root = Some(root);
} else {
commands.entity(root).despawn();
}
}
}
if let Some(root) = matching_root {
commands.entity(root).insert(SkinnedMaterialsDirty);
continue;
}
let resolved_path = if renderer.asset_id.trim().is_empty() {
renderer.path.clone()
} else {
match skinned_mesh_source_path(&renderer.asset_id) {
Ok(path) => path,
Err(error) => {
warn!(
"SkinnedMeshRenderer {entity} could not resolve stable asset {}: {error}; falling back to cached path {}",
renderer.asset_id, renderer.path
);
renderer.path.clone()
}
}
};
let path = asset_server_path(&resolved_path);
let handle = if path.to_ascii_lowercase().ends_with(".fbx") {
asset_server.load(SkinnedMeshRenderer::fbx_scene_asset_path(
&path,
renderer.scene_index,
))
} else {
asset_server.load(GltfAssetLabel::Scene(renderer.scene_index).from_asset(path))
};
commands.spawn((
Name::new("Hydrated Skinned Mesh Root"),
HydratedSkinnedMeshRoot { owner: entity },
requested_source,
WorldAssetRoot(handle),
ChildOf(entity),
));
}
}
/// Defers material application until the imported world has produced its actual draw entities.
pub(super) fn mark_skinned_materials_ready(
ready: On<WorldInstanceReady>,
roots: Query<(), With<HydratedSkinnedMeshRoot>>,
mut commands: Commands,
) {
if roots.get(ready.entity).is_ok() {
commands.entity(ready.entity).insert(SkinnedMaterialsDirty);
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn apply_skinned_renderer_material_changes(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut artifact_cache: ResMut<StaticMeshArtifactCache>,
dirty_roots: Query<(Entity, &HydratedSkinnedMeshRoot), With<SkinnedMaterialsDirty>>,
renderers: Query<&SkinnedMeshRenderer>,
children: Query<&Children>,
parents: Query<&ChildOf>,
names: Query<&Name>,
meshes: Query<(Entity, &Mesh3d)>,
) {
for (root_entity, root) in &dirty_roots {
let Ok(renderer) = renderers.get(root.owner) else {
commands
.entity(root_entity)
.remove::<SkinnedMaterialsDirty>();
continue;
};
let descendants = collect_descendants(root_entity, &children);
let mut candidates = Vec::new();
for entity in descendants {
let Ok((_, mesh)) = meshes.get(entity) else {
continue;
};
let label = asset_server
.get_path(mesh.id())
.and_then(|path| path.label().map(str::to_string));
let hierarchy_path = hierarchy_path(entity, root_entity, &parents, &names);
candidates.push((entity, label, hierarchy_path));
}
let mut used = std::collections::HashSet::new();
for slot in &renderer.materials.slots {
let Some(binding) = artifact_cache.resolve_draw_binding(&renderer.asset_id, &slot.id)
else {
warn!(
"Skinned material slot '{}' has no generated draw binding for asset {}",
slot.id.0, renderer.asset_id
);
continue;
};
let matched = candidates
.iter()
.filter(|(entity, label, _)| {
!used.contains(entity) && label.as_deref() == Some(binding.mesh_label.as_str())
})
.find(|(_, _, path)| {
binding
.source_node
.as_deref()
.is_none_or(|source| path.ends_with(source))
})
.or_else(|| {
candidates.iter().find(|(entity, label, _)| {
!used.contains(entity)
&& label.as_deref() == Some(binding.mesh_label.as_str())
})
});
let Some((entity, _, _)) = matched else {
warn!(
"Skinned material slot '{}' could not find hydrated mesh {} ({:?})",
slot.id.0, binding.mesh_label, binding.source_node
);
continue;
};
used.insert(*entity);
let effective = slot.effective_material().cloned();
let Some(reference) = effective.as_ref() else {
commands
.entity(*entity)
.insert(HydratedRendererMaterialBinding {
owner: root.owner,
slot_id: slot.id.clone(),
effective_material: None,
});
continue;
};
let handle = resolve_renderer_material_handle(
&asset_server,
&mut materials,
&mut artifact_cache,
reference,
)
.unwrap_or_else(|| renderer_error_material(&mut materials));
commands.entity(*entity).insert((
MeshMaterial3d(handle),
HydratedRendererMaterialBinding {
owner: root.owner,
slot_id: slot.id.clone(),
effective_material: effective,
},
));
}
commands
.entity(root_entity)
.remove::<SkinnedMaterialsDirty>();
}
}
fn collect_descendants(root: Entity, children: &Query<&Children>) -> Vec<Entity> {
let mut result = Vec::new();
let mut pending = vec![root];
while let Some(entity) = pending.pop() {
if entity != root {
result.push(entity);
}
if let Ok(entity_children) = children.get(entity) {
pending.extend(entity_children.iter());
}
}
result
}
fn hierarchy_path(
mut entity: Entity,
root: Entity,
parents: &Query<&ChildOf>,
names: &Query<&Name>,
) -> String {
let mut segments = Vec::new();
while entity != root {
if let Ok(name) = names.get(entity) {
segments.push(name.as_str().to_string());
}
let Ok(parent) = parents.get(entity) else {
break;
};
entity = parent.parent();
}
segments.reverse();
segments.join("/")
}
/// Removes generated roots if the authoring renderer is removed without another renderer change.
pub(super) fn cleanup_removed_skinned_mesh_renderers(
mut commands: Commands,
renderers: Query<
(Option<&AuthoringComponentStates>, Option<&InspectorOrder>),
With<SkinnedMeshRenderer>,
>,
roots: Query<(Entity, &HydratedSkinnedMeshRoot)>,
) {
for (root_entity, root) in &roots {
let active = renderers
.get(root.owner)
.is_ok_and(|(states, legacy_order)| {
authoring_component_active(states, legacy_order, COMPONENT_SKINNED_MESH_RENDERER)
});
if !active {
commands.entity(root_entity).despawn();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use bevy::asset::{AssetApp, AssetPlugin};
use bevy::prelude::WorldAsset;
use std::path::{Path, PathBuf};
struct TestManifest(PathBuf);
impl Drop for TestManifest {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn write_test_manifest(asset_id: &str, source_path: &str) -> TestManifest {
let path = PathBuf::from(skinned_mesh_manifest_path(asset_id));
std::fs::create_dir_all(path.parent().expect("manifest has a parent directory"))
.expect("generated animation directory should be writable");
std::fs::write(&path, format!(r#"(source: (path: "{source_path}"))"#))
.expect("test animation manifest should be writable");
TestManifest(path)
}
fn hydration_app() -> App {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
.init_asset::<WorldAsset>()
.add_systems(
Update,
(
hydrate_skinned_mesh_renderers,
cleanup_removed_skinned_mesh_renderers,
)
.chain(),
);
app
}
fn generated_roots(world: &mut World, owner: Entity) -> Vec<Entity> {
world
.query::<(Entity, &HydratedSkinnedMeshRoot)>()
.iter(world)
.filter_map(|(entity, root)| (root.owner == owner).then_some(entity))
.collect()
}
#[test]
fn renderer_hydrates_a_dedicated_root_and_preserves_authored_children() {
let mut app = hydration_app();
let owner = app
.world_mut()
.spawn((
LevelObject,
SkinnedMeshRenderer::new("assets/models/character.glb"),
))
.id();
let authored_child = app
.world_mut()
.spawn((Name::new("Socket"), ChildOf(owner)))
.id();
app.update();
assert_eq!(generated_roots(app.world_mut(), owner).len(), 1);
assert!(app.world().get_entity(authored_child).is_ok());
}
#[test]
fn stable_asset_id_uses_animation_artifact_source() {
const ASSET_ID: &str = "fe1ea62f-9ca8-40c6-a747-a1f40567b8c6";
let _manifest = write_test_manifest(ASSET_ID, "assets/models/relocated/hero.glb");
let mut app = hydration_app();
let owner = app
.world_mut()
.spawn((
LevelObject,
SkinnedMeshRenderer::new("assets/models/stale.glb").with_asset_id(ASSET_ID),
))
.id();
app.update();
let root_entity = generated_roots(app.world_mut(), owner)[0];
let root = app.world().get::<WorldAssetRoot>(root_entity).unwrap();
let loaded_path = app
.world()
.resource::<AssetServer>()
.get_path(root.0.id())
.unwrap();
assert_eq!(loaded_path.path(), Path::new("models/relocated/hero.glb"));
assert_eq!(loaded_path.label(), Some("Scene0"));
}
#[test]
fn removing_renderer_despawns_only_its_generated_root() {
let mut app = hydration_app();
let owner = app
.world_mut()
.spawn((
LevelObject,
SkinnedMeshRenderer::new("assets/models/character.glb"),
))
.id();
app.update();
let root = generated_roots(app.world_mut(), owner)[0];
app.world_mut()
.entity_mut(owner)
.remove::<SkinnedMeshRenderer>();
app.update();
assert!(app.world().get_entity(root).is_err());
assert!(app.world().get_entity(owner).is_ok());
}
#[test]
fn disabling_renderer_removes_hydrated_root_and_reenable_restores_it() {
let mut app = hydration_app();
let owner = app
.world_mut()
.spawn((
LevelObject,
SkinnedMeshRenderer::new("assets/models/character.glb"),
AuthoringComponentStates::default(),
))
.id();
app.update();
assert_eq!(generated_roots(app.world_mut(), owner).len(), 1);
app.world_mut()
.get_mut::<AuthoringComponentStates>(owner)
.unwrap()
.set_component_active(COMPONENT_SKINNED_MESH_RENDERER, false);
app.update();
assert!(generated_roots(app.world_mut(), owner).is_empty());
app.world_mut()
.get_mut::<AuthoringComponentStates>(owner)
.unwrap()
.set_component_active(COMPONENT_SKINNED_MESH_RENDERER, true);
app.update();
assert_eq!(generated_roots(app.world_mut(), owner).len(), 1);
}
}
+253 -18
View File
@@ -3,13 +3,16 @@
use avian3d::prelude::ColliderConstructor;
use bevy::light::{NotShadowCaster, NotShadowReceiver};
use bevy::prelude::*;
use bevy::render::render_resource::Face;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use crate::{
asset_server_path, inspector_component_active, standard_material_asset_path, ColliderDesc,
ColliderShapeDesc, EditorAssetRef, InspectorOrder, LevelObject, MaterialDesc, MaterialOverride,
StaticMeshRenderer, StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
asset_server_path, authoring_component_active, standard_material_asset_path,
AuthoringComponentStates, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialAsset,
MaterialDesc, MaterialInstanceAsset, MaterialOverride, MaterialRef, StaticMeshRenderer,
StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
COMPONENT_STATIC_MESH_RENDERER,
};
@@ -35,16 +38,39 @@ struct ResolvedStaticMeshMaterial {
material_label: String,
}
#[derive(Debug, Clone)]
pub(crate) struct ResolvedRendererDraw {
pub mesh_label: String,
pub source_node: Option<String>,
}
/// Cache for generated static mesh artifact lookups.
#[derive(Resource, Default)]
pub struct StaticMeshArtifactCache {
parts: HashMap<(String, String), ResolvedStaticMeshPart>,
materials: HashMap<(String, String), ResolvedStaticMeshMaterial>,
draw_bindings: HashMap<(String, String), ResolvedRendererDraw>,
loaded_assets: HashSet<String>,
failed_assets: HashSet<String>,
project_materials: HashMap<MaterialRef, Handle<StandardMaterial>>,
}
impl StaticMeshArtifactCache {
pub(crate) fn resolve_draw_binding(
&mut self,
asset_id: &str,
slot_id: &crate::ComponentInstanceId,
) -> Option<ResolvedRendererDraw> {
let key = (asset_id.to_string(), slot_id.0.clone());
if let Some(binding) = self.draw_bindings.get(&key) {
return Some(binding.clone());
}
if !self.loaded_assets.contains(asset_id) && !self.failed_assets.contains(asset_id) {
self.load_artifact(asset_id);
}
self.draw_bindings.get(&key).cloned()
}
fn resolve(&mut self, mesh: &EditorAssetRef) -> Option<ResolvedStaticMeshPart> {
if !mesh.is_resolved() {
return None;
@@ -95,17 +121,18 @@ impl StaticMeshArtifactCache {
} else {
part.id.clone()
};
self.parts.insert(
(asset_id.to_string(), part_id),
ResolvedStaticMeshPart {
source_path: manifest.source.path.clone(),
let slot_id = format!("slot:{part_id}");
self.draw_bindings.insert(
(asset_id.to_string(), slot_id),
ResolvedRendererDraw {
mesh_label: part.mesh_label.clone(),
material_label: part.material_label.clone(),
source_node: part.source_node.clone(),
},
);
if let Some(material_label) = part.material_label {
if let Some(material_label) = part.material_label.clone() {
let material_id = part
.material_id
.clone()
.filter(|id| !id.trim().is_empty())
.unwrap_or_else(|| material_id_from_label(&material_label));
self.materials
@@ -115,6 +142,24 @@ impl StaticMeshArtifactCache {
material_label,
});
}
if part.skinned
|| manifest.metadata.animation_count > 0
|| manifest.metadata.skin_count > 0
{
warn!(
"Static mesh artifact part {} requires an animated/skinned hierarchy and was excluded from StaticMeshRenderer hydration",
part.mesh_label
);
continue;
}
self.parts.insert(
(asset_id.to_string(), part_id),
ResolvedStaticMeshPart {
source_path: manifest.source.path.clone(),
mesh_label: part.mesh_label.clone(),
material_label: part.material_label.clone(),
},
);
}
self.loaded_assets.insert(asset_id.to_string());
}
@@ -130,9 +175,19 @@ impl StaticMeshArtifactCache {
struct StaticMeshResolveManifest {
source: StaticMeshResolveSource,
#[serde(default)]
metadata: StaticMeshResolveMetadata,
#[serde(default)]
parts: Vec<StaticMeshResolvePart>,
}
#[derive(Debug, Default, Deserialize)]
struct StaticMeshResolveMetadata {
#[serde(default)]
animation_count: usize,
#[serde(default)]
skin_count: usize,
}
#[derive(Debug, Deserialize)]
struct StaticMeshResolveSource {
path: String,
@@ -147,6 +202,10 @@ struct StaticMeshResolvePart {
material_id: Option<String>,
#[serde(default)]
material_label: Option<String>,
#[serde(default)]
source_node: Option<String>,
#[serde(default)]
skinned: bool,
}
#[allow(clippy::type_complexity)]
@@ -162,6 +221,7 @@ pub fn hydrate_static_mesh_renderers(
Option<&MaterialDesc>,
Option<&MaterialOverride>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
@@ -172,6 +232,7 @@ pub fn hydrate_static_mesh_renderers(
Changed<MaterialDesc>,
Changed<MaterialOverride>,
Changed<ColliderDesc>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
@@ -179,15 +240,17 @@ pub fn hydrate_static_mesh_renderers(
children: Query<&Children>,
generated_parts: Query<(), With<HydratedStaticMeshPart>>,
) {
for (entity, renderer, parent_material, material_override, collider, order) in &renderers {
for (entity, renderer, parent_material, material_override, collider, states, order) in
&renderers
{
despawn_static_mesh_parts(&mut commands, entity, &children, &generated_parts);
if !inspector_component_active(order, COMPONENT_STATIC_MESH_RENDERER) {
if !authoring_component_active(states, order, COMPONENT_STATIC_MESH_RENDERER) {
continue;
}
let parent_material =
parent_material.filter(|_| inspector_component_active(order, COMPONENT_MATERIAL_DESC));
let parent_material = parent_material
.filter(|_| authoring_component_active(states, order, COMPONENT_MATERIAL_DESC));
let collider =
collider.filter(|_| inspector_component_active(order, COMPONENT_COLLIDER_DESC));
collider.filter(|_| authoring_component_active(states, order, COMPONENT_COLLIDER_DESC));
spawn_static_mesh_parts(
&mut commands,
&asset_server,
@@ -237,6 +300,7 @@ pub fn spawn_static_mesh_parts(
asset_server,
materials,
artifact_cache,
renderer,
entry,
&resolved,
parent_material,
@@ -253,6 +317,11 @@ pub fn spawn_static_mesh_parts(
Name::new(name),
Mesh3d(mesh_handle),
MeshMaterial3d(material_handle),
HydratedRendererMaterialBinding {
owner: parent,
slot_id: effective_material_slot_id(entry),
effective_material: effective_material_ref(renderer, entry).cloned(),
},
entry.local_transform,
Visibility::Visible,
ChildOf(parent),
@@ -296,6 +365,7 @@ fn material_for_entry(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
artifact_cache: &mut StaticMeshArtifactCache,
renderer: &StaticMeshRenderer,
entry: &StaticMeshRendererEntry,
resolved: &ResolvedStaticMeshPart,
parent_material: Option<&MaterialDesc>,
@@ -315,8 +385,13 @@ fn material_for_entry(
return materials.add(material_from_desc(asset_server, override_material));
}
if let Some(material_ref) = entry.material.as_ref() {
if let Some(resolved_material) = artifact_cache.resolve_material(material_ref) {
if let Some(material_ref) = effective_material_ref(renderer, entry) {
if let Some(handle) =
resolve_shared_material(asset_server, materials, artifact_cache, material_ref)
{
return handle;
}
if let Some(resolved_material) = artifact_cache.resolve_material(&material_ref.0) {
let source_path = asset_server_path(&resolved_material.source_path);
return asset_server.load(standard_material_asset_path(
&source_path,
@@ -325,16 +400,121 @@ fn material_for_entry(
}
debug!(
"Static mesh material ref unresolved: asset_id='{}' material='{}' label='{}'",
material_ref.asset_id, material_ref.sub_asset_id, material_ref.label
material_ref.0.asset_id, material_ref.0.sub_asset_id, material_ref.0.label
);
}
// Read-only compatibility path for schema-v1/v2 scenes. The explicit project upgrader moves
// this reference into `RendererMaterialSet` and clears the legacy draw-part field.
if let Some(material_ref) = entry.material.as_ref() {
let material_ref = MaterialRef::new(material_ref.clone());
if let Some(handle) =
resolve_shared_material(asset_server, materials, artifact_cache, &material_ref)
{
return handle;
}
if let Some(resolved_material) = artifact_cache.resolve_material(&material_ref.0) {
let source_path = asset_server_path(&resolved_material.source_path);
return asset_server.load(standard_material_asset_path(
&source_path,
&resolved_material.material_label,
));
}
}
if let Some(label) = resolved.material_label.as_deref() {
let source_path = asset_server_path(&resolved.source_path);
return asset_server.load(standard_material_asset_path(&source_path, label));
}
materials.add(StandardMaterial::default())
materials.add(error_material())
}
fn effective_material_slot_id(entry: &StaticMeshRendererEntry) -> crate::ComponentInstanceId {
if entry.material_slot_id.0.trim().is_empty() {
entry.id.clone()
} else {
entry.material_slot_id.clone()
}
}
fn effective_material_ref<'a>(
renderer: &'a StaticMeshRenderer,
entry: &'a StaticMeshRendererEntry,
) -> Option<&'a MaterialRef> {
let slot_id = effective_material_slot_id(entry);
renderer.materials.effective_material(&slot_id)
}
fn resolve_shared_material(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
cache: &mut StaticMeshArtifactCache,
reference: &MaterialRef,
) -> Option<Handle<StandardMaterial>> {
if let Some(handle) = cache.project_materials.get(reference) {
return Some(handle.clone());
}
let path = reference.0.source_path.as_deref()?;
let desc_and_state = MaterialAsset::load_from_path(path)
.map(|asset| (asset.material, asset.render_state))
.or_else(|_| {
let instance = MaterialInstanceAsset::load_from_path(path)?;
let base_path = instance.base.0.source_path.as_deref().ok_or_else(|| {
format!(
"material instance {} has no loadable base path",
instance.label
)
})?;
let base = MaterialAsset::load_from_path(base_path)?;
let mut desc = base.material;
instance.apply_to(&mut desc);
Ok::<_, String>((desc, base.render_state))
})
.ok()?;
let mut material = material_from_desc(asset_server, &desc_and_state.0);
material.alpha_mode = match desc_and_state.1.alpha_mode {
MaterialAlphaMode::Opaque => AlphaMode::Opaque,
MaterialAlphaMode::Cutout => AlphaMode::Mask(desc_and_state.1.alpha_cutoff),
};
material.cull_mode = (!desc_and_state.1.double_sided).then_some(Face::Back);
let handle = materials.add(material);
cache
.project_materials
.insert(reference.clone(), handle.clone());
Some(handle)
}
pub(crate) fn resolve_renderer_material_handle(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
cache: &mut StaticMeshArtifactCache,
reference: &MaterialRef,
) -> Option<Handle<StandardMaterial>> {
if let Some(handle) = resolve_shared_material(asset_server, materials, cache, reference) {
return Some(handle);
}
let resolved = cache.resolve_material(&reference.0)?;
let source_path = asset_server_path(&resolved.source_path);
Some(asset_server.load(standard_material_asset_path(
&source_path,
&resolved.material_label,
)))
}
pub(crate) fn renderer_error_material(
materials: &mut Assets<StandardMaterial>,
) -> Handle<StandardMaterial> {
materials.add(error_material())
}
fn error_material() -> StandardMaterial {
StandardMaterial {
base_color: Color::srgb(1.0, 0.0, 1.0),
perceptual_roughness: 0.35,
metallic: 0.0,
..default()
}
}
fn labeled_asset_path(path: &str, label: &str) -> String {
@@ -392,3 +572,58 @@ fn stable_sub_asset_slug(label: &str) -> String {
}
slug.trim_matches('_').to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
struct TestManifest(PathBuf);
impl Drop for TestManifest {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn write_manifest(asset_id: &str, animation_count: usize, skinned: bool) -> TestManifest {
let path = PathBuf::from(static_mesh_manifest_path(asset_id));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
format!(
r#"(
source: (path: "assets/models/test.glb"),
metadata: (animation_count: {animation_count}),
parts: [(
id: "mesh:test",
mesh_label: "Mesh0/Primitive0",
skinned: {skinned},
)],
)"#
),
)
.unwrap();
TestManifest(path)
}
#[test]
fn cache_refuses_skin_bound_parts() {
const ASSET_ID: &str = "7cd29974-1503-4084-b4a0-7483d0a57d7d";
let _manifest = write_manifest(ASSET_ID, 0, true);
let mut cache = StaticMeshArtifactCache::default();
let reference = EditorAssetRef::new(ASSET_ID, "mesh:test", "Test");
assert!(cache.resolve(&reference).is_none());
}
#[test]
fn cache_refuses_geometry_from_animated_sources() {
const ASSET_ID: &str = "7f6fcf6a-e978-4dc6-8738-16d52fc3ed03";
let _manifest = write_manifest(ASSET_ID, 1, false);
let mut cache = StaticMeshArtifactCache::default();
let reference = EditorAssetRef::new(ASSET_ID, "mesh:test", "Test");
assert!(cache.resolve(&reference).is_none());
}
}
+108 -3
View File
@@ -10,8 +10,10 @@ pub mod brush_math;
mod components;
mod hydration;
mod material_asset;
mod navigation;
mod post_process_effect_asset;
mod prefab_overrides;
mod renderer_material;
mod rendering_profile_asset;
pub use actor::{infer_actor_kind, validate_actor, ActorValidationError};
@@ -20,17 +22,21 @@ pub use components::*;
pub use hydration::{
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
strip_hydrated, strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember,
HydratedPrefabReady, HydrationPlugin, PrefabHydrationBlocked,
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydrationPlugin, PrefabHydrationBlocked,
};
pub use material_asset::{
MaterialAsset, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset, MaterialRenderState,
ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset, MATERIAL_ASSET_SCHEMA_VERSION,
MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
};
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,
};
pub use renderer_material::*;
pub use rendering_profile_asset::RenderingProfileAsset;
/// Converts catalog-style paths (`assets/models/foo.fbx`) to Bevy AssetServer paths.
@@ -73,14 +79,25 @@ impl Plugin for SharedTypesPlugin {
.register_type::<SubsceneReference>()
.register_type::<HierarchySiblingIndex>()
.register_type::<InspectorOrder>()
.register_type::<AuthoringComponentStates>()
.register_type::<InspectorComponentState>()
.register_type::<ComponentInstanceId>()
.register_type::<EditorAssetRef>()
.register_type::<MaterialRef>()
.register_type::<RendererMaterialSlot>()
.register_type::<RendererMaterialSet>()
.register_type::<OrphanedMaterialAssignment>()
.register_type::<AnimationSkeletonSignature>()
.register_type::<SkinnedMeshRenderer>()
.register_type::<AnimationPlaybackRange>()
.register_type::<AnimationEventDesc>()
.register_type::<AnimationStateDesc>()
.register_type::<AnimationControllerDesc>()
.register_type::<NavigationAgentProfile>()
.register_type::<NavigationBounds>()
.register_type::<NavigationObstacle>()
.register_type::<NavigationArea>()
.register_type::<NavigationLink>()
.register_type::<AudioSourceDesc>()
.register_type::<AudioListenerDesc>()
.register_type::<AudioAttenuationDesc>()
@@ -127,13 +144,37 @@ impl Plugin for SharedTypesPlugin {
.register_type::<PostProcessVolumeOverrides>()
.register_type::<TeamSpawn>()
.register_type::<ObjectiveMarker>()
.add_systems(Update, migrate_legacy_authoring_component_states)
.add_plugins(HydrationPlugin);
}
}
fn migrate_legacy_authoring_component_states(
mut commands: Commands,
mut legacy: Query<
(Entity, &mut InspectorOrder),
(With<LevelObject>, Without<AuthoringComponentStates>),
>,
) {
for (entity, mut order) in &mut legacy {
let mut states = std::mem::take(&mut order.component_states);
for state in &mut states {
if state.component_id.is_empty() {
if let Some(component_id) = authoring_component_id(&state.type_name) {
state.component_id = component_id.to_string();
state.type_name.clear();
}
}
}
commands
.entity(entity)
.insert(AuthoringComponentStates { states });
}
}
#[cfg(test)]
mod tests {
use super::standard_material_asset_path;
use super::*;
#[test]
fn gltf_standard_material_paths_use_pbr_conversion_label() {
@@ -162,4 +203,68 @@ mod tests {
"models/robot.glb#Material3/std"
);
}
#[test]
fn legacy_inspector_active_state_moves_to_authoring_component_states() {
let mut app = App::new();
app.add_systems(Update, migrate_legacy_authoring_component_states);
let mut order = InspectorOrder::default();
order.component_states.push(InspectorComponentState {
component_id: String::new(),
type_name: COMPONENT_LIGHT_DESC.to_string(),
active: false,
});
let entity = app.world_mut().spawn((LevelObject, order)).id();
app.update();
let states = app.world().get::<AuthoringComponentStates>(entity).unwrap();
assert!(!states.is_component_active(COMPONENT_LIGHT_DESC));
assert_eq!(states.states[0].component_id, AUTHORING_COMPONENT_LIGHT);
assert!(states.states[0].type_name.is_empty());
assert!(app
.world()
.get::<InspectorOrder>(entity)
.unwrap()
.component_states
.is_empty());
}
#[test]
fn new_active_state_takes_precedence_over_legacy_order() {
let mut legacy = InspectorOrder::default();
legacy.set_component_active(COMPONENT_LIGHT_DESC, false);
let mut states = AuthoringComponentStates::default();
states.set_component_active(COMPONENT_LIGHT_DESC, true);
assert!(authoring_component_active(
Some(&states),
Some(&legacy),
COMPONENT_LIGHT_DESC
));
}
#[test]
fn inspector_order_migrates_legacy_type_paths_to_stable_ids_on_edit() {
let present = [COMPONENT_LIGHT_DESC, COMPONENT_PRIMITIVE];
let mut order = InspectorOrder {
component_type_names: present.iter().map(|value| value.to_string()).collect(),
..Default::default()
};
assert_eq!(order.ordered_components(&present), present);
assert!(order.move_component(COMPONENT_PRIMITIVE, -1, &present));
assert!(order.component_type_names.is_empty());
assert_eq!(
order.component_ids,
vec![
AUTHORING_COMPONENT_PRIMITIVE.to_string(),
AUTHORING_COMPONENT_LIGHT.to_string()
]
);
assert_eq!(
order.ordered_components(&present),
vec![COMPONENT_PRIMITIVE, COMPONENT_LIGHT_DESC]
);
}
}
+211 -4
View File
@@ -1,15 +1,73 @@
//! Serializable material asset files under `assets/materials/`.
//! Versioned material, material-instance, and surface-shader asset documents.
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{MaterialDesc, MaterialParameter, MaterialShaderKind, MaterialTextureBinding};
use crate::{
EditorAssetRef, MaterialDesc, MaterialParameter, MaterialRef, MaterialShaderKind,
MaterialTextureBinding,
};
pub const MATERIAL_ASSET_SCHEMA_VERSION: u32 = 1;
pub const MATERIAL_INSTANCE_SCHEMA_VERSION: u32 = 1;
pub const SURFACE_SHADER_SCHEMA_VERSION: u32 = 1;
const fn default_material_schema_version() -> u32 {
MATERIAL_ASSET_SCHEMA_VERSION
}
const fn default_material_instance_schema_version() -> u32 {
MATERIAL_INSTANCE_SCHEMA_VERSION
}
const fn default_surface_shader_schema_version() -> u32 {
SURFACE_SHADER_SCHEMA_VERSION
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum MaterialAlphaMode {
#[default]
Opaque,
Cutout,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub struct MaterialRenderState {
#[serde(default)]
pub alpha_mode: MaterialAlphaMode,
#[serde(default = "default_alpha_cutoff")]
pub alpha_cutoff: f32,
#[serde(default)]
pub double_sided: bool,
}
const fn default_alpha_cutoff() -> f32 {
0.5
}
impl Default for MaterialRenderState {
fn default() -> Self {
Self {
alpha_mode: MaterialAlphaMode::Opaque,
alpha_cutoff: default_alpha_cutoff(),
double_sided: false,
}
}
}
/// RON material asset: label plus authoring [`MaterialDesc`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize)]
pub struct MaterialAsset {
#[serde(default = "default_material_schema_version")]
pub schema_version: u32,
pub label: String,
/// Legacy path/label retained for v0 compatibility. New assets use `shader_ref`.
#[serde(default)]
pub shader: Option<String>,
#[serde(default)]
pub shader_ref: Option<EditorAssetRef>,
#[serde(default)]
pub render_state: MaterialRenderState,
pub material: MaterialDesc,
}
@@ -21,6 +79,81 @@ impl MaterialAsset {
}
}
/// Explicit reusable overrides over one project Material asset.
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MaterialInstanceAsset {
#[serde(default = "default_material_instance_schema_version")]
pub schema_version: u32,
pub label: String,
pub base: MaterialRef,
#[serde(default)]
pub parameters: Vec<MaterialParameter>,
#[serde(default)]
pub textures: Vec<MaterialTextureBinding>,
}
impl MaterialInstanceAsset {
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 material-instance RON in {catalog_path}: {err}"))
}
/// Applies this instance's sparse overrides without mutating the shared base asset.
pub fn apply_to(&self, material: &mut MaterialDesc) {
for parameter in &self.parameters {
match (parameter.name.as_str(), &parameter.value) {
("base_color", crate::MaterialParameterValue::Color(value)) => {
material.base_color = *value;
}
("metallic", crate::MaterialParameterValue::Float(value)) => {
material.metallic = *value;
}
("roughness", crate::MaterialParameterValue::Float(value)) => {
material.roughness = *value;
}
("emissive_color", crate::MaterialParameterValue::Color(value)) => {
material.emissive_color = *value;
}
("emissive_intensity", crate::MaterialParameterValue::Float(value)) => {
material.emissive_intensity = *value;
}
_ => upsert_parameter(&mut material.parameters, parameter.clone()),
}
}
for texture in &self.textures {
let path = texture
.texture
.as_ref()
.and_then(|reference| reference.source_path.clone());
match texture.name.as_str() {
"base_color_texture" => material.base_color_texture = path,
"emissive_texture" => material.emissive_texture = path,
"normal_map_texture" => material.normal_map_texture = path,
"metallic_roughness_texture" => material.metallic_roughness_texture = path,
_ => upsert_texture(&mut material.textures, texture.clone()),
}
}
}
}
fn upsert_parameter(values: &mut Vec<MaterialParameter>, value: MaterialParameter) {
if let Some(existing) = values.iter_mut().find(|entry| entry.name == value.name) {
*existing = value;
} else {
values.push(value);
}
}
fn upsert_texture(values: &mut Vec<MaterialTextureBinding>, value: MaterialTextureBinding) {
if let Some(existing) = values.iter_mut().find(|entry| entry.name == value.name) {
*existing = value;
} else {
values.push(value);
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ShaderPropertyType {
Bool,
@@ -42,8 +175,10 @@ pub struct ShaderPropertyDesc {
}
/// RON shader schema describing material inspector parameters.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ShaderSchemaAsset {
#[serde(default = "default_surface_shader_schema_version")]
pub schema_version: u32,
pub label: String,
pub kind: MaterialShaderKind,
#[serde(default)]
@@ -56,6 +191,78 @@ pub struct ShaderSchemaAsset {
pub default_textures: Vec<MaterialTextureBinding>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_material_defaults_to_current_schema_and_opaque() {
let parsed: MaterialAsset = ron::from_str(
r#"(label: "Legacy", material: (base_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), metallic: 0.0, roughness: 0.5, base_color_texture: None, normal_map_texture: None, metallic_roughness_texture: None))"#,
)
.expect("legacy material should remain readable");
assert_eq!(parsed.schema_version, MATERIAL_ASSET_SCHEMA_VERSION);
assert_eq!(parsed.render_state.alpha_mode, MaterialAlphaMode::Opaque);
}
#[test]
fn material_instance_requires_an_explicit_base_ref() {
let instance = MaterialInstanceAsset {
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Red Variant".into(),
base: MaterialRef::new(EditorAssetRef::new(
"material-id",
"material:source",
"Base",
)),
parameters: Vec::new(),
textures: Vec::new(),
};
assert!(instance.base.is_resolved());
}
#[test]
fn material_instance_applies_standard_and_custom_overrides() {
let mut material = MaterialDesc::default();
let instance = MaterialInstanceAsset {
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Variant".into(),
base: MaterialRef::default(),
parameters: vec![
MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.2),
},
MaterialParameter {
name: "edge_width".into(),
value: crate::MaterialParameterValue::Float(3.0),
},
],
textures: vec![MaterialTextureBinding {
name: "base_color_texture".into(),
texture: Some(
EditorAssetRef::new("texture", "texture:source", "Grid")
.with_source_path("assets/textures/grid.png"),
),
}],
};
instance.apply_to(&mut material);
assert_eq!(material.roughness, 0.2);
assert_eq!(
material.base_color_texture.as_deref(),
Some("assets/textures/grid.png")
);
assert!(material
.parameters
.iter()
.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)
+181
View File
@@ -0,0 +1,181 @@
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
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";
pub const COMPONENT_NAVIGATION_LINK: &str = "shared::navigation::NavigationLink";
/// Agent dimensions and deterministic Rerecast bake settings.
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct NavigationAgentProfile {
pub id: String,
pub radius: f32,
pub height: f32,
pub max_climb: f32,
pub max_slope_deg: f32,
pub cell_size_fraction: f32,
pub cell_height_fraction: f32,
pub min_region_size: u16,
pub merge_region_size: u16,
}
impl Default for NavigationAgentProfile {
fn default() -> Self {
Self {
id: "humanoid".into(),
radius: 0.35,
height: 1.8,
max_climb: 0.45,
max_slope_deg: 45.0,
cell_size_fraction: 3.0,
cell_height_fraction: 6.0,
min_region_size: 4,
merge_region_size: 12,
}
}
}
impl NavigationAgentProfile {
pub fn validate(&self) -> Result<(), &'static str> {
if self.id.trim().is_empty() {
return Err("agent profile ID must not be empty");
}
if !self.radius.is_finite() || self.radius <= 0.0 {
return Err("agent radius must be finite and greater than zero");
}
if !self.height.is_finite() || self.height <= self.radius * 2.0 {
return Err("agent height must be finite and greater than twice its radius");
}
if !self.max_climb.is_finite() || self.max_climb < 0.0 || self.max_climb >= self.height {
return Err("maximum climb must be finite, non-negative, and below agent height");
}
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_height_fraction.is_finite() || self.cell_height_fraction <= 0.0 {
return Err("cell height fraction must be finite and greater than zero");
}
Ok(())
}
}
/// Axis-aligned world region baked for one agent profile.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct NavigationBounds {
pub half_extents: Vec3,
pub agent: NavigationAgentProfile,
pub artifact_path: String,
#[serde(default)]
pub auto_bake: bool,
}
impl Default for NavigationBounds {
fn default() -> Self {
Self {
half_extents: Vec3::new(20.0, 4.0, 20.0),
agent: NavigationAgentProfile::default(),
artifact_path: "assets/navigation/generated/main_humanoid.nav.ron".into(),
auto_bake: false,
}
}
}
/// Axis-aligned volume carved from every overlapping navigation bake.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct NavigationObstacle {
pub half_extents: Vec3,
#[serde(default)]
pub dynamic: bool,
}
impl Default for NavigationObstacle {
fn default() -> Self {
Self {
half_extents: Vec3::splat(0.5),
dynamic: false,
}
}
}
/// Named navigation area volume retained in the bake artifact.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct NavigationArea {
pub id: String,
pub half_extents: Vec3,
pub cost: f32,
#[serde(default = "default_true")]
pub walkable: bool,
}
impl Default for NavigationArea {
fn default() -> Self {
Self {
id: "default".into(),
half_extents: Vec3::splat(1.0),
cost: 1.0,
walkable: true,
}
}
}
/// Explicit off-mesh connection. Endpoints are local to the owning actor.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct NavigationLink {
pub start: Vec3,
pub end: Vec3,
#[serde(default = "default_true")]
pub bidirectional: bool,
#[serde(default = "default_one")]
pub cost: f32,
#[serde(default = "default_true")]
pub enabled: bool,
}
impl Default for NavigationLink {
fn default() -> Self {
Self {
start: Vec3::ZERO,
end: Vec3::new(0.0, 0.0, 2.0),
bidirectional: true,
cost: 1.0,
enabled: true,
}
}
}
fn default_true() -> bool {
true
}
fn default_one() -> f32 {
1.0
}
#[cfg(test)]
mod tests {
use super::NavigationAgentProfile;
#[test]
fn default_agent_profile_is_valid() {
assert_eq!(NavigationAgentProfile::default().validate(), Ok(()));
}
#[test]
fn invalid_agent_dimensions_are_actionable() {
let mut profile = NavigationAgentProfile::default();
profile.height = profile.radius;
assert_eq!(
profile.validate(),
Err("agent height must be finite and greater than twice its radius")
);
}
}
+155
View File
@@ -0,0 +1,155 @@
//! Shared material references and renderer-slot authoring contracts.
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{ComponentInstanceId, EditorAssetRef, MaterialParameter, MaterialTextureBinding};
/// A stable reference to a project material, material instance, or imported material subasset.
///
/// The registry UUID/subasset ID are authoritative. `EditorAssetRef::source_path` is only a
/// load-time cache and may be repaired when an asset moves.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterialRef(pub EditorAssetRef);
impl MaterialRef {
pub fn new(asset: EditorAssetRef) -> Self {
Self(asset)
}
pub fn is_resolved(&self) -> bool {
self.0.is_resolved()
}
}
impl From<EditorAssetRef> for MaterialRef {
fn from(value: EditorAssetRef) -> Self {
Self(value)
}
}
/// One stable, named material assignment exposed by a renderer.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct RendererMaterialSlot {
pub id: ComponentInstanceId,
pub name: String,
/// Read-only imported default. Clearing `material` returns to this reference.
#[serde(default)]
pub source_material: Option<MaterialRef>,
/// Explicit shared Material or Material Instance assignment.
#[serde(default)]
pub material: Option<MaterialRef>,
}
impl RendererMaterialSlot {
pub fn effective_material(&self) -> Option<&MaterialRef> {
self.material.as_ref().or(self.source_material.as_ref())
}
}
/// Assignment retained after a source reimport removes or renames its draw slot.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct OrphanedMaterialAssignment {
pub slot_id: ComponentInstanceId,
#[serde(default)]
pub last_known_name: String,
pub material: MaterialRef,
}
/// Material slots shared by static and skinned renderer authoring components.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct RendererMaterialSet {
#[serde(default)]
pub slots: Vec<RendererMaterialSlot>,
#[serde(default)]
pub orphaned_assignments: Vec<OrphanedMaterialAssignment>,
}
impl RendererMaterialSet {
pub fn slot(&self, id: &ComponentInstanceId) -> Option<&RendererMaterialSlot> {
self.slots.iter().find(|slot| &slot.id == id)
}
pub fn slot_mut(&mut self, id: &ComponentInstanceId) -> Option<&mut RendererMaterialSlot> {
self.slots.iter_mut().find(|slot| &slot.id == id)
}
pub fn effective_material(&self, id: &ComponentInstanceId) -> Option<&MaterialRef> {
self.slot(id)
.and_then(RendererMaterialSlot::effective_material)
}
}
/// Runtime-only property overrides analogous to a material property block.
///
/// Blocks never alter shared assets and are deliberately excluded from scene/prefab persistence.
#[derive(Reflect, Default, Debug, Clone, PartialEq)]
#[reflect(Default, Debug, PartialEq)]
pub struct MaterialPropertyBlock {
pub slot_id: ComponentInstanceId,
#[reflect(ignore)]
pub parameters: Vec<MaterialParameter>,
#[reflect(ignore)]
pub textures: Vec<MaterialTextureBinding>,
}
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq)]
pub struct MaterialPropertyBlocks {
pub slots: Vec<MaterialPropertyBlock>,
}
/// Runtime ownership/binding marker placed on every hydrated renderer draw entity.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Eq)]
#[reflect(Component, Debug, PartialEq)]
pub struct HydratedRendererMaterialBinding {
pub owner: Entity,
pub slot_id: ComponentInstanceId,
pub effective_material: Option<MaterialRef>,
}
#[cfg(test)]
mod tests {
use super::*;
fn material_ref(id: &str) -> MaterialRef {
MaterialRef::new(EditorAssetRef::new(id, "material:source", id))
}
#[test]
fn explicit_assignment_precedes_imported_source() {
let source = material_ref("source");
let assigned = material_ref("assigned");
let mut slot = RendererMaterialSlot {
id: ComponentInstanceId::new("slot:body"),
name: "Body".into(),
source_material: Some(source.clone()),
material: Some(assigned.clone()),
};
assert_eq!(slot.effective_material(), Some(&assigned));
slot.material = None;
assert_eq!(slot.effective_material(), Some(&source));
}
#[test]
fn missing_slot_does_not_fall_back_by_display_name() {
let set = RendererMaterialSet {
slots: vec![RendererMaterialSlot {
id: ComponentInstanceId::new("slot:body"),
name: "Body".into(),
source_material: Some(material_ref("source")),
material: None,
}],
orphaned_assignments: vec![],
};
assert!(set
.effective_material(&ComponentInstanceId::new("slot:renamed"))
.is_none());
}
}