use crate::api::RoadNetwork;
use crate::common::MaliputError;
use std::error::Error;
use std::fs::{create_dir_all, read_to_string, remove_file};
use std::path::{Path, PathBuf};
pub type ObjFeatures = maliput_sys::utility::ffi::Features;
pub fn generate_obj_file(
road_network: &RoadNetwork,
dirpath: impl AsRef<Path>,
fileroot: impl AsRef<str>,
obj_features: &ObjFeatures,
) -> Result<PathBuf, MaliputError> {
let future_obj_file_path = dirpath.as_ref().join(fileroot.as_ref().to_string() + ".obj");
let dirpath = to_string(dirpath).map_err(|e| MaliputError::ObjCreationError(e.to_string()))?;
create_dir_all(&dirpath).map_err(|e| MaliputError::ObjCreationError(e.to_string()))?;
let raw_rn = road_network.rn.as_ref();
if let Some(raw_rn) = raw_rn {
unsafe {
maliput_sys::utility::ffi::Utility_GenerateObjFile(
raw_rn,
&dirpath,
&fileroot.as_ref().to_string(),
obj_features,
)
.map_err(|e| MaliputError::ObjCreationError(e.to_string()))?;
}
if future_obj_file_path.is_file() && future_obj_file_path.with_extension("mtl").is_file() {
Ok(future_obj_file_path)
} else {
Result::Err(MaliputError::ObjCreationError(String::from(
"Failed to generate the Wavefront files.",
)))
}
} else {
Result::Err(MaliputError::ObjCreationError(String::from("RoadNetwork is empty.")))
}
}
pub fn get_obj_description_from_road_network(
road_network: &RoadNetwork,
obj_features: &ObjFeatures,
) -> Result<String, Box<dyn Error>> {
let output_directory = std::env::temp_dir().join("maliput");
create_dir_all(&output_directory)?;
let file_name = String::from("road_network");
let path_to_obj_file = generate_obj_file(road_network, &output_directory, &file_name, obj_features)?;
let obj_description = read_to_string(&path_to_obj_file)?;
remove_file(path_to_obj_file.clone())?;
let mtl_full_path = path_to_obj_file.with_extension("mtl");
remove_file(mtl_full_path)?;
Ok(obj_description)
}
fn to_string(path: impl AsRef<Path>) -> Result<String, &'static str> {
Ok(path
.as_ref()
.as_os_str()
.to_str()
.ok_or("Failed to get output directory.")?
.to_string())
}