Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion crates/rmf_site_editor/src/sdf_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ fn compute_model_source<'a, 'b>(
) -> Result<AssetSource, SdfError> {
// SDF can reference models with the model:// syntax, which specifies a path relative to a certain
// model, in the shape of model://ModelName/path_to_file.ext
let asset_source = if let Some(stripped) = subasset_uri.strip_prefix("model://") {
let mut asset_source = if let Some(stripped) = subasset_uri.strip_prefix("model://") {
let mut asset_source =
AssetSource::try_from(load_context.asset_path().to_string().as_str())
.map_err(SdfError::UnsupportedAssetSource)?;
Expand Down Expand Up @@ -169,6 +169,11 @@ fn compute_model_source<'a, 'b>(
.or_else(|e| Err(SdfError::UnsupportedAssetSource(e.to_string())))?;
AssetSource::try_from(path.to_string().as_str()).map_err(SdfError::UnsupportedAssetSource)
}?;
// AssetPath joins paths with the platform separator, so on Windows the result
// may contain `\`. Remote and search sources are always `/`-separated names.
if let AssetSource::Remote(ref mut p) | AssetSource::Search(ref mut p) = asset_source {
*p = p.replace('\\', "/");
}
Ok(asset_source)
}

Expand Down
36 changes: 21 additions & 15 deletions crates/rmf_site_editor/src/site/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,14 @@ pub struct SceneHandle(pub UntypedHandle);
pub fn spawn_scene_for_loaded_model(
In((parent, h, source)): In<(Entity, UntypedHandle, AssetSource)>,
world: &mut World,
) -> Option<(Entity, bool)> {
) -> Result<(Entity, bool), ModelLoadingErrorKind> {
// The parent may have been despawned while its asset was loading, e.g. when
// a sub-model of a scene is removed because the scene's source changed.
// TODO(@xiyuoh) make this into a feature
world.entity_mut(parent).insert(SceneHandle(h.clone()));
world
.get_entity_mut(parent)
.map_err(|_| ModelLoadingErrorKind::ParentDespawned)?
.insert(SceneHandle(h.clone()));
// For each model that is loading, check if its scene has finished loading
// yet. If the scene has finished loading, then insert it as a child of the
// model entity and make it selectable.
Expand All @@ -218,14 +223,17 @@ pub fn spawn_scene_for_loaded_model(
// Note we can't do an `if let Some()` because get(Handle) panics if the type is
// not the stored type
let gltfs = world.resource::<Assets<Gltf>>();
let gltf = gltfs.get(h.typed::<Gltf>().id())?;
let gltf = gltfs
.get(h.typed::<Gltf>().id())
.ok_or(ModelLoadingErrorKind::NonModelAsset)?;
// Get default scene if present, otherwise index 0
let scene = gltf
.default_scene
.as_ref()
.or_else(|| gltf.scenes.get(0))
.cloned()?;
Some((
.cloned()
.ok_or(ModelLoadingErrorKind::NonModelAsset)?;
Ok((
world
.spawn((
SceneRoot(scene),
Expand All @@ -237,7 +245,7 @@ pub fn spawn_scene_for_loaded_model(
))
} else if type_id == TypeId::of::<Scene>() {
let scene = h.typed::<Scene>();
Some((
Ok((
world
.spawn((
SceneRoot(scene),
Expand All @@ -250,7 +258,7 @@ pub fn spawn_scene_for_loaded_model(
} else if type_id == TypeId::of::<Mesh>() {
let site_assets = world.resource::<SiteAssets>();
let mesh = h.typed::<Mesh>();
Some((
Ok((
world
.spawn((
Mesh3d(mesh),
Expand All @@ -261,7 +269,7 @@ pub fn spawn_scene_for_loaded_model(
false,
))
} else {
None
Err(ModelLoadingErrorKind::NonModelAsset)
}?;
// Add scene and visibility bundle if not present already
world
Expand All @@ -274,7 +282,7 @@ pub fn spawn_scene_for_loaded_model(
if world.get::<Visibility>(parent).is_none() {
world.entity_mut(parent).insert(Visibility::default());
}
Some((model_id, is_scene))
Ok((model_id, is_scene))
}

/// Return Ok(request) if the source changed and we might need to continue downstream operations.
Expand Down Expand Up @@ -358,12 +366,8 @@ fn handle_model_loading(
ModelLoadingErrorKind::WorkflowExecutionError,
)
})?;
let Some((scene_entity, is_scene)) = res else {
return Err(ModelLoadingError::new(
request.clone(),
ModelLoadingErrorKind::NonModelAsset,
));
};
let (scene_entity, is_scene) =
res.map_err(|kind| ModelLoadingError::new(request.clone(), kind))?;
if is_scene {
// Wait for the scene to be spawned, if there is one
channel
Expand Down Expand Up @@ -749,6 +753,8 @@ pub enum ModelLoadingErrorKind {
FailedLoadingAsset,
#[error("Asset did not contain a model")]
NonModelAsset,
#[error("Model entity was despawned before its asset finished loading")]
ParentDespawned,
#[error("Failed loading dependency for model, error: {0}")]
FailedLoadingDependency(String),
}
Expand Down
41 changes: 39 additions & 2 deletions crates/rmf_site_editor/src/site_asset_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ fn load_from_file<'a>(path: PathBuf) -> Result<Box<dyn Reader>, AssetReaderError
}
}

/// Converts an asset path into a name that always uses `/` as the separator.
/// Bevy joins paths with the platform separator, so on Windows a resolved
/// path such as `OpenRobotics/Model/meshes/mesh.obj` may arrive as
/// `OpenRobotics\Model\meshes\mesh.obj`, which breaks fuel URL generation.
fn asset_name_from_path(path: &Path) -> String {
path.iter()
.map(|c| c.to_string_lossy())
.collect::<Vec<_>>()
.join("/")
}

fn generate_remote_asset_url(name: &str) -> Result<String, AssetReaderError> {
// Expected format: OrgName/ModelName/FileName.ext
// We may need to be a bit magical here because some assets
Expand Down Expand Up @@ -263,7 +274,7 @@ impl Plugin for SiteAssetIoPlugin {
// Relative to a cache directory
// Attempt to fetch from the server and save it to the cache directory

let asset_name = path.to_str().unwrap().to_owned();
let asset_name = asset_name_from_path(path);
if let Ok(paths) = get_path_from_env() {
// Check if file exists
for path in paths.iter() {
Expand Down Expand Up @@ -300,7 +311,7 @@ impl Plugin for SiteAssetIoPlugin {
"rmf-server",
BevyAssetSource::build().with_reader(|| {
Box::new(SiteAssetReader::new(|path: &Path| {
let asset_name = path.to_str().unwrap().to_owned();
let asset_name = asset_name_from_path(path);
let remote_url: String = match generate_remote_asset_url(&asset_name) {
Ok(uri) => uri,
Err(e) => return Box::pin(async move { Err(e) }),
Expand Down Expand Up @@ -358,3 +369,29 @@ impl Plugin for SiteAssetIoPlugin {
);
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn asset_name_uses_forward_slashes() {
let expected = "OpenRobotics/AdjTable/meshes/AdjTable.obj";
assert_eq!(asset_name_from_path(Path::new(expected)), expected);

let mut path = PathBuf::from("OpenRobotics");
path.push("AdjTable");
path.push("meshes");
path.push("AdjTable.obj");
assert_eq!(asset_name_from_path(&path), expected);
}

#[test]
fn remote_url_from_asset_name() {
let uri = generate_remote_asset_url("OpenRobotics/AdjTable/meshes/AdjTable.obj").unwrap();
assert_eq!(
uri,
"https://fuel.gazebosim.org/1.0/OpenRobotics/models/AdjTable/tip/files/meshes/AdjTable.obj"
);
}
}