Upgrade to Bevy 0.19 and harden editor workflows
CI / Format, lint, test, build (push) Has been cancelled

This commit is contained in:
Rbanh committed 2026-07-09 23:43:47 -04:00
1 parent 3f85d25cc7
commit b5e561904c
204 files changed
+6972 -29907

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FbxError {
#[error("Failed to read FBX file: {0}")]
Io(#[from] std::io::Error),
#[error("Failed to load FBX: {0}")]
UfbxError(String),
#[error("Failed to convert FBX data: {0}")]
ConversionError(String),
#[error("Failed to convert mesh: {0}")]
MeshConversion(String),
#[error("Failed to convert material: {0}")]
MaterialConversion(String),
#[error("Failed to load texture: {0}")]
TextureLoad(String),
#[error("Invalid FBX data: {0}")]
InvalidData(String),
#[error("Unsupported FBX feature: {0}")]
UnsupportedFeature(String),
}
+63
View File
@@ -0,0 +1,63 @@
//! Labels that can be used to load part of an FBX asset
use bevy::asset::AssetPath;
/// Labels that can be used to load part of an FBX asset
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxAssetLabel {
/// `Scene{}`: FBX Scene as a Bevy [`Scene`](bevy::scene::Scene)
Scene(usize),
/// `Mesh{}`: FBX Mesh as a Bevy [`Mesh`](bevy::render::mesh::Mesh)
Mesh(usize),
/// `Material{}`: FBX material as a Bevy [`StandardMaterial`](bevy::pbr::StandardMaterial)
Material(usize),
/// `Animation{}`: FBX animation as a Bevy [`AnimationClip`](bevy::animation::AnimationClip)
Animation(usize),
/// `AnimationStack{}`: FBX animation stack with multiple layers
AnimationStack(usize),
/// `Skeleton{}`: FBX skeleton for skeletal animation
Skeleton(usize),
/// `Node{}`: Individual FBX node in the scene hierarchy
Node(usize),
/// `Skin{}`: FBX skin for skeletal animation
Skin(usize),
/// `Light{}`: FBX light definition
Light(usize),
/// `Camera{}`: FBX camera definition
Camera(usize),
/// `Texture{}`: FBX texture reference
Texture(usize),
/// `DefaultScene`: Main scene with all objects
DefaultScene,
/// `DefaultMaterial`: Fallback material used when no material is present
DefaultMaterial,
/// `RootNode`: Root node of the scene hierarchy
RootNode,
}
impl core::fmt::Display for FbxAssetLabel {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FbxAssetLabel::Scene(index) => f.write_str(&format!("Scene{index}")),
FbxAssetLabel::Mesh(index) => f.write_str(&format!("Mesh{index}")),
FbxAssetLabel::Material(index) => f.write_str(&format!("Material{index}")),
FbxAssetLabel::Animation(index) => f.write_str(&format!("Animation{index}")),
FbxAssetLabel::AnimationStack(index) => f.write_str(&format!("AnimationStack{index}")),
FbxAssetLabel::Skeleton(index) => f.write_str(&format!("Skeleton{index}")),
FbxAssetLabel::Node(index) => f.write_str(&format!("Node{index}")),
FbxAssetLabel::Skin(index) => f.write_str(&format!("Skin{index}")),
FbxAssetLabel::Light(index) => f.write_str(&format!("Light{index}")),
FbxAssetLabel::Camera(index) => f.write_str(&format!("Camera{index}")),
FbxAssetLabel::Texture(index) => f.write_str(&format!("Texture{index}")),
FbxAssetLabel::DefaultScene => f.write_str("DefaultScene"),
FbxAssetLabel::DefaultMaterial => f.write_str("DefaultMaterial"),
FbxAssetLabel::RootNode => f.write_str("RootNode"),
}
}
}
impl FbxAssetLabel {
/// Add this label to an asset path
pub fn from_asset(&self, path: impl Into<AssetPath<'static>>) -> AssetPath<'static> {
path.into().with_label(self.to_string())
}
}
+53
View File
@@ -0,0 +1,53 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![forbid(unsafe_code)]
#![doc(
html_logo_url = "https://bevyengine.org/assets/icon.png",
html_favicon_url = "https://bevyengine.org/assets/icon.png"
)]
//! Loader for FBX scenes using [`ufbx`](https://github.com/ufbx/ufbx-rust).
//!
//! This plugin provides comprehensive FBX file loading support for Bevy, including:
//! - Mesh geometry with multi-material support
//! - PBR materials with textures
//! - Skeletal animation and skinning
//! - Scene hierarchy with nodes
//! - Lights and cameras
//! - Animation clips with curves
use bevy::asset::AssetApp;
use bevy::prelude::*;
pub mod error;
pub mod label;
pub mod loader;
pub mod material;
pub mod mesh;
pub mod node;
pub mod scene;
pub mod types;
pub mod utils;
pub use error::FbxError;
pub use label::FbxAssetLabel;
pub use loader::{FbxLoader, FbxLoaderSettings};
pub use types::*;
pub mod prelude {
//! Commonly used items.
pub use crate::{Fbx, FbxAssetLabel, FbxLoaderSettings, FbxNode, FbxPlugin, FbxSkin, Skeleton};
}
/// Plugin adding the FBX loader to an [`App`].
#[derive(Default)]
pub struct FbxPlugin;
impl Plugin for FbxPlugin {
fn build(&self, app: &mut App) {
app.init_asset::<Fbx>()
.init_asset::<FbxNode>()
.init_asset::<FbxSkin>()
.init_asset::<Skeleton>()
.register_asset_loader(FbxLoader::default());
}
}
+150
View File
@@ -0,0 +1,150 @@
//! FBX loader implementation for Bevy.
use crate::error::FbxError;
use crate::material::process_materials;
use crate::mesh::process_meshes;
use crate::node::{process_nodes, process_skins};
use crate::scene::build_scene;
use crate::types::{Fbx, FbxAxisSystem, FbxMeta, Handedness};
use bevy::asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Settings for FBX file loading.
///
/// These settings allow customizing which parts of the FBX file are loaded
/// and how they are processed.
#[derive(Serialize, Deserialize)]
pub struct FbxLoaderSettings {
/// How meshes should be loaded and used
pub load_meshes: RenderAssetUsages,
/// How materials should be loaded and used
pub load_materials: RenderAssetUsages,
/// Whether to load cameras from the FBX file
pub load_cameras: bool,
/// Whether to load lights from the FBX file
pub load_lights: bool,
/// Whether to include raw source data in the loaded asset
pub include_source: bool,
/// Whether to convert coordinate systems (e.g., Y-up to Z-up)
pub convert_coordinates: bool,
}
impl Default for FbxLoaderSettings {
fn default() -> Self {
Self {
load_meshes: RenderAssetUsages::default(),
load_materials: RenderAssetUsages::default(),
load_cameras: true,
load_lights: true,
include_source: false,
convert_coordinates: false,
}
}
}
/// Loader implementation for FBX files.
///
/// This loader handles reading FBX files and converting them into Bevy assets,
/// including meshes, materials, animations, and scene hierarchies.
#[derive(Default, bevy::reflect::TypePath)]
pub struct FbxLoader;
impl AssetLoader for FbxLoader {
type Asset = Fbx;
type Settings = FbxLoaderSettings;
type Error = FbxError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Fbx, FbxError> {
// Read file
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
// Basic validation
if bytes.is_empty() {
return Err(FbxError::InvalidData("Empty FBX file".to_string()));
}
if bytes.len() < 32 {
return Err(FbxError::InvalidData("FBX file too small".to_string()));
}
// Parse with ufbx
// Provide the asset path as a filename hint so ufbx can compute relative_filename
let filename_hint = load_context.path().path().to_string_lossy().to_string();
let root = ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
filename: ufbx::StringOpt::Ref(&filename_hint),
..Default::default()
},
)
.map_err(|e| FbxError::UfbxError(format!("{:?}", e)))?;
let scene: &ufbx::Scene = &*root;
// Process meshes
let (meshes, named_meshes, mesh_transforms, mesh_material_info) =
process_meshes(scene, settings, load_context)?;
// Process materials and textures
let (materials, named_materials) = if !settings.load_materials.is_empty() {
process_materials(scene, settings, load_context)?
} else {
(Vec::new(), HashMap::new())
};
// Process nodes and hierarchy
let (nodes, named_nodes, node_map) = process_nodes(scene, &meshes, load_context)?;
// Process skins
let (skins, named_skins) = process_skins(scene, &node_map, load_context)?;
// Build scene
let scene_handle = build_scene(
scene,
&meshes,
&materials,
&named_materials,
&mesh_transforms,
&mesh_material_info,
settings,
load_context,
)?;
// Extract metadata
let metadata = FbxMeta::default();
// Build final FBX asset
Ok(Fbx {
scenes: vec![scene_handle.clone()],
named_scenes: HashMap::new(),
meshes,
named_meshes,
materials,
named_materials,
nodes,
named_nodes,
skins,
named_skins,
default_scene: Some(scene_handle),
axis_system: FbxAxisSystem {
up: Vec3::Y,
front: Vec3::Z,
handedness: Handedness::Right,
},
unit_scale: 1.0,
metadata,
})
}
fn extensions(&self) -> &[&str] {
&["fbx"]
}
}
+246
View File
@@ -0,0 +1,246 @@
//! Material and texture processing for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::loader::FbxLoaderSettings;
use crate::utils::convert_texture_uv_transform;
use bevy::asset::{Handle, LoadContext};
use bevy::pbr::StandardMaterial;
use bevy::prelude::*;
use bevy_material::AlphaMode;
use bevy_image::{CompressedImageFormats, ImageSampler, ImageType};
use std::collections::HashMap;
/// Process all materials from the FBX scene.
pub fn process_materials(
scene: &ufbx::Scene,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<
(
Vec<Handle<StandardMaterial>>,
HashMap<Box<str>, Handle<StandardMaterial>>,
),
FbxError,
> {
let mut materials = Vec::new();
let mut named_materials = HashMap::new();
let texture_handles = process_textures(scene, settings, load_context)?;
for (index, ufbx_material) in scene.materials.as_ref().iter().enumerate() {
if ufbx_material.element.element_id == 0 {
continue;
}
let standard_material = create_standard_material(ufbx_material, &texture_handles)?;
let handle = load_context.add_labeled_asset(
FbxAssetLabel::Material(index).to_string(),
standard_material,
);
if !ufbx_material.element.name.is_empty() {
named_materials.insert(
Box::from(ufbx_material.element.name.as_ref()),
handle.clone(),
);
}
materials.push(handle);
}
Ok((materials, named_materials))
}
/// Process textures from materials.
///
/// Uses the following priority for each texture:
/// 1. Embedded textures (`texture.content` non-empty) — decoded via `Image::from_buffer`
/// 2. External textures via `texture.relative_filename` — already relative to the FBX file
/// 3. External textures via `.fbm` folder extraction from `texture.filename` / `texture.absolute_filename`
pub fn process_textures(
scene: &ufbx::Scene,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<HashMap<u32, Handle<Image>>, FbxError> {
let mut texture_handles = HashMap::new();
for (index, texture) in scene.textures.as_ref().iter().enumerate() {
let asset_path = load_context.path().clone();
let fbx_dir = asset_path
.path()
.parent()
.unwrap_or_else(|| std::path::Path::new(""))
.to_path_buf();
// Priority 1: Embedded texture data
if !texture.content.is_empty() {
let ext = extract_extension(&texture.filename).unwrap_or("png");
match Image::from_buffer(
&texture.content,
ImageType::Extension(ext),
CompressedImageFormats::NONE,
true, // is_srgb
ImageSampler::Default,
settings.load_materials,
) {
Ok(image) => {
let handle = load_context.add_labeled_asset(
FbxAssetLabel::Texture(index).to_string(),
image,
);
texture_handles.insert(texture.element.element_id, handle);
continue;
}
Err(e) => {
eprintln!("bevy_ufbx: failed to load embedded texture {index}: {e}");
// Fall through to try external paths
}
}
}
// Priority 2: relative_filename from ufbx (relative to FBX file)
if !texture.relative_filename.is_empty() {
let rel = texture.relative_filename.as_ref();
let is_absolute = rel.starts_with('/')
|| (rel.len() >= 3 && rel.chars().nth(1) == Some(':'));
if !is_absolute {
let texture_path = fbx_dir.join(rel).to_string_lossy().to_string();
let image_handle = load_context.load(texture_path);
texture_handles.insert(texture.element.element_id, image_handle);
continue;
}
}
// Priority 3: Extract relative path from filename / absolute_filename
// Preserves .fbm folder structure if present (e.g., "model.fbm/texture.jpg")
let relative_path = extract_relative_texture_path(texture);
if !relative_path.is_empty() {
let texture_path = fbx_dir
.join(relative_path)
.to_string_lossy()
.to_string();
let image_handle = load_context.load(texture_path);
texture_handles.insert(texture.element.element_id, image_handle);
}
}
Ok(texture_handles)
}
/// Extract file extension from a texture filename string.
fn extract_extension(filename: &ufbx::String) -> Option<&str> {
if filename.is_empty() {
return None;
}
let s = filename.as_ref();
s.rsplit('.')
.next()
.filter(|ext| !ext.contains('/') && !ext.contains('\\'))
}
/// Extract a relative texture path from a ufbx Texture's filename or absolute_filename.
///
/// Handles absolute paths by looking for `.fbm` folders (FBX's standard embedded texture
/// directory) and extracting from there, or falling back to just the filename.
fn extract_relative_texture_path<'a>(texture: &'a ufbx::Texture) -> &'a str {
if !texture.filename.is_empty() {
let filename = texture.filename.as_ref();
let is_absolute = filename.starts_with('/')
|| (filename.len() >= 3 && filename.chars().nth(1) == Some(':'));
if is_absolute {
extract_from_absolute(filename)
} else {
filename
}
} else if !texture.absolute_filename.is_empty() {
extract_from_absolute(texture.absolute_filename.as_ref())
} else {
""
}
}
/// Extract a relative path from an absolute path, preserving `.fbm` folder structure.
fn extract_from_absolute(path: &str) -> &str {
if let Some(fbm_pos) = path.rfind(".fbm/").or_else(|| path.rfind(".fbm\\")) {
let before_fbm = &path[..fbm_pos];
let folder_start = before_fbm
.rfind(&['/', '\\'][..])
.map(|p| p + 1)
.unwrap_or(0);
&path[folder_start..]
} else {
let last_slash = path.rfind(&['/', '\\'][..]);
if let Some(pos) = last_slash {
&path[pos + 1..]
} else {
path
}
}
}
/// Create a StandardMaterial from ufbx material.
pub fn create_standard_material(
ufbx_material: &ufbx::Material,
texture_handles: &HashMap<u32, Handle<Image>>,
) -> Result<StandardMaterial, FbxError> {
let mut material = StandardMaterial::default();
// Base color
if let Ok(diffuse) = std::panic::catch_unwind(|| ufbx_material.fbx.diffuse_color.value_vec4) {
material.base_color = Color::srgb(diffuse.x as f32, diffuse.y as f32, diffuse.z as f32);
} else if let Ok(pbr_base) =
std::panic::catch_unwind(|| ufbx_material.pbr.base_color.value_vec4)
{
material.base_color = Color::srgb(pbr_base.x as f32, pbr_base.y as f32, pbr_base.z as f32);
}
// Metallic and roughness
if let Ok(metallic) = std::panic::catch_unwind(|| ufbx_material.pbr.metalness.value_vec4) {
material.metallic = metallic.x as f32;
}
if let Ok(roughness) = std::panic::catch_unwind(|| ufbx_material.pbr.roughness.value_vec4) {
material.perceptual_roughness = roughness.x as f32;
}
// Emission
if let Ok(emission) = std::panic::catch_unwind(|| ufbx_material.fbx.emission_color.value_vec4) {
material.emissive =
LinearRgba::rgb(emission.x as f32, emission.y as f32, emission.z as f32);
}
// Alpha
if ufbx_material.pbr.opacity.value_vec4.x < 1.0 {
let alpha = ufbx_material.pbr.opacity.value_vec4.x as f32;
material.alpha_mode = if alpha < 0.98 {
AlphaMode::Blend
} else {
AlphaMode::Opaque
};
}
// Textures
for texture_ref in &ufbx_material.textures {
if let Some(image_handle) = texture_handles.get(&texture_ref.texture.element.element_id) {
match texture_ref.material_prop.as_ref() {
"DiffuseColor" | "BaseColor" => {
material.base_color_texture = Some(image_handle.clone());
material.uv_transform = convert_texture_uv_transform(&texture_ref.texture);
}
"NormalMap" => material.normal_map_texture = Some(image_handle.clone()),
"Metallic" => material.metallic_roughness_texture = Some(image_handle.clone()),
"Roughness" if material.metallic_roughness_texture.is_none() => {
material.metallic_roughness_texture = Some(image_handle.clone());
}
"EmissiveColor" => material.emissive_texture = Some(image_handle.clone()),
"AmbientOcclusion" => material.occlusion_texture = Some(image_handle.clone()),
_ => {}
}
}
}
Ok(material)
}
+218
View File
@@ -0,0 +1,218 @@
//! Mesh processing functionality for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::loader::FbxLoaderSettings;
use bevy::asset::{Handle, LoadContext};
use bevy::prelude::*;
use bevy::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};
use std::collections::HashMap;
/// Process all meshes from the FBX scene.
pub fn process_meshes(
scene: &ufbx::Scene,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<
(
Vec<Handle<Mesh>>,
HashMap<Box<str>, Handle<Mesh>>,
Vec<ufbx::Matrix>,
Vec<Vec<String>>,
),
FbxError,
> {
let mut meshes = Vec::new();
let mut named_meshes = HashMap::new();
let mut transforms = Vec::new();
let mut mesh_material_info = Vec::new();
for (index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let mesh = mesh_ref.as_ref();
if mesh.num_vertices == 0 || mesh.faces.as_ref().is_empty() {
continue;
}
// Group faces by material
let material_groups = group_faces_by_material(mesh);
// Create mesh for each material group
for (material_idx, indices) in material_groups.iter() {
let mesh_handle = create_mesh_from_group(
mesh,
indices,
index,
*material_idx,
settings,
load_context,
)?;
if *material_idx == 0 && !node.element.name.is_empty() {
named_meshes.insert(Box::from(node.element.name.as_ref()), mesh_handle.clone());
}
meshes.push(mesh_handle);
transforms.push(node.geometry_to_world);
let material_name = if *material_idx < mesh.materials.len() {
mesh.materials[*material_idx].element.name.to_string()
} else {
"default".to_string()
};
mesh_material_info.push(vec![material_name]);
}
}
Ok((meshes, named_meshes, transforms, mesh_material_info))
}
/// Group mesh faces by material index.
pub fn group_faces_by_material(mesh: &ufbx::Mesh) -> HashMap<usize, Vec<u32>> {
let mut material_groups: HashMap<usize, Vec<u32>> = HashMap::new();
let mut scratch = Vec::new();
if mesh.materials.is_empty() {
// No materials - create single group
let mut all_indices = Vec::new();
for &face in mesh.faces.as_ref().iter() {
scratch.clear();
ufbx::triangulate_face_vec(&mut scratch, mesh, face);
for idx in &scratch {
if (*idx as usize) < mesh.vertex_indices.len() {
all_indices.push(mesh.vertex_indices[*idx as usize]);
}
}
}
material_groups.insert(0, all_indices);
} else {
// Group by material
for (face_idx, &face) in mesh.faces.as_ref().iter().enumerate() {
let material_idx =
if !mesh.face_material.is_empty() && face_idx < mesh.face_material.len() {
mesh.face_material[face_idx] as usize
} else {
0
};
scratch.clear();
ufbx::triangulate_face_vec(&mut scratch, mesh, face);
let indices = material_groups.entry(material_idx).or_insert_with(Vec::new);
for idx in &scratch {
if (*idx as usize) < mesh.vertex_indices.len() {
indices.push(mesh.vertex_indices[*idx as usize]);
}
}
}
}
material_groups
}
/// Create a Bevy mesh from a material group.
pub fn create_mesh_from_group(
ufbx_mesh: &ufbx::Mesh,
indices: &[u32],
mesh_index: usize,
material_index: usize,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<Handle<Mesh>, FbxError> {
let label = FbxAssetLabel::Mesh(mesh_index * 1000 + material_index).to_string();
let handle = load_context.labeled_asset_scope(label, |_| {
let mut bevy_mesh = Mesh::new(PrimitiveTopology::TriangleList, settings.load_meshes);
// Positions
let positions: Vec<[f32; 3]> = ufbx_mesh
.vertex_position
.values
.as_ref()
.iter()
.map(|v| [v.x as f32, v.y as f32, v.z as f32])
.collect();
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
// Normals
if ufbx_mesh.vertex_normal.exists {
let normals: Vec<[f32; 3]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let n = ufbx_mesh.vertex_normal[i];
[n.x as f32, n.y as f32, n.z as f32]
})
.collect();
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
}
// UVs
if ufbx_mesh.vertex_uv.exists {
let uvs: Vec<[f32; 2]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let uv = ufbx_mesh.vertex_uv[i];
[uv.x as f32, uv.y as f32]
})
.collect();
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
}
// Skinning
if !ufbx_mesh.skin_deformers.is_empty() {
process_skinning_data(ufbx_mesh, &mut bevy_mesh);
}
// Indices
bevy_mesh.insert_indices(Indices::U32(indices.to_vec()));
Ok::<_, FbxError>(bevy_mesh)
})?;
Ok(handle)
}
/// Process skinning data for a mesh.
pub fn process_skinning_data(ufbx_mesh: &ufbx::Mesh, bevy_mesh: &mut Mesh) {
let skin_deformer = &ufbx_mesh.skin_deformers[0];
let mut joint_indices = vec![[0u16; 4]; ufbx_mesh.num_vertices];
let mut joint_weights = vec![[0.0f32; 4]; ufbx_mesh.num_vertices];
for vertex_index in 0..ufbx_mesh.num_vertices {
let mut weight_count = 0;
let mut total_weight = 0.0f32;
for (cluster_index, cluster) in skin_deformer.clusters.iter().enumerate() {
if weight_count >= 4 {
break;
}
for (i, &vert_idx) in cluster.vertices.iter().enumerate() {
if vert_idx as usize == vertex_index && i < cluster.weights.len() {
let weight = cluster.weights[i] as f32;
if weight > 0.0 {
joint_indices[vertex_index][weight_count] = cluster_index as u16;
joint_weights[vertex_index][weight_count] = weight;
total_weight += weight;
weight_count += 1;
break;
}
}
}
}
// Normalize weights
if total_weight > 0.0 {
for i in 0..weight_count {
joint_weights[vertex_index][i] /= total_weight;
}
}
}
bevy_mesh.insert_attribute(
Mesh::ATTRIBUTE_JOINT_INDEX,
VertexAttributeValues::Uint16x4(joint_indices),
);
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_JOINT_WEIGHT, joint_weights);
}
+135
View File
@@ -0,0 +1,135 @@
//! Node and hierarchy processing for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::types::{FbxNode, FbxSkin};
use crate::utils::{convert_matrix, convert_transform};
use bevy::asset::{Handle, LoadContext};
use bevy::prelude::*;
use bevy::mesh::skinning::SkinnedMeshInverseBindposes;
use std::collections::HashMap;
/// Process nodes and build hierarchy.
pub fn process_nodes(
scene: &ufbx::Scene,
meshes: &[Handle<Mesh>],
load_context: &mut LoadContext,
) -> Result<
(
Vec<Handle<FbxNode>>,
HashMap<Box<str>, Handle<FbxNode>>,
HashMap<u32, Handle<FbxNode>>,
),
FbxError,
> {
let mut nodes = Vec::new();
let mut named_nodes = HashMap::new();
let mut node_map = HashMap::new();
// First pass: create nodes
for (index, ufbx_node) in scene.nodes.as_ref().iter().enumerate() {
let name = if ufbx_node.element.name.is_empty() {
format!("Node_{}", index)
} else {
ufbx_node.element.name.to_string()
};
let mesh_handle = if ufbx_node.mesh.is_some() && index < meshes.len() {
Some(meshes[index].clone())
} else {
None
};
let fbx_node = FbxNode {
index,
name: name.clone(),
children: Vec::new(),
mesh: mesh_handle,
skin: None,
transform: convert_transform(&ufbx_node.local_transform),
visible: ufbx_node.visible,
};
let handle =
load_context.add_labeled_asset(FbxAssetLabel::Node(index).to_string(), fbx_node);
node_map.insert(ufbx_node.element.element_id, handle.clone());
nodes.push(handle.clone());
if !ufbx_node.element.name.is_empty() {
named_nodes.insert(Box::from(ufbx_node.element.name.as_ref()), handle);
}
}
// Note: Hierarchy building would require mutable access to nodes
// which is not possible with the current asset system.
// Parent-child relationships would need to be established at runtime.
Ok((nodes, named_nodes, node_map))
}
/// Process skins for skeletal animation.
pub fn process_skins(
scene: &ufbx::Scene,
node_map: &HashMap<u32, Handle<FbxNode>>,
load_context: &mut LoadContext,
) -> Result<(Vec<Handle<FbxSkin>>, HashMap<Box<str>, Handle<FbxSkin>>), FbxError> {
let mut skins = Vec::new();
let mut named_skins = HashMap::new();
for (skin_index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = &node.mesh else {
continue;
};
let mesh = mesh_ref.as_ref();
if mesh.skin_deformers.is_empty() {
continue;
}
let skin_deformer = &mesh.skin_deformers[0];
let mut inverse_bind_matrices = Vec::new();
let mut joint_handles = Vec::new();
for cluster in &skin_deformer.clusters {
let bind_matrix = convert_matrix(&cluster.bind_to_world);
inverse_bind_matrices.push(bind_matrix.inverse());
if let Some(bone_node) = cluster.bone_node.as_ref() {
if let Some(joint_handle) = node_map.get(&bone_node.element.element_id) {
joint_handles.push(joint_handle.clone());
}
}
}
if !inverse_bind_matrices.is_empty() {
let inverse_bindposes_handle = load_context.add_labeled_asset(
format!("Skin_{}_InverseBindposes", skin_index),
SkinnedMeshInverseBindposes::from(inverse_bind_matrices),
);
let skin_name = if node.element.name.is_empty() {
format!("Skin_{}", skin_index)
} else {
format!("{}_Skin", node.element.name)
};
let fbx_skin = FbxSkin {
index: skin_index,
name: skin_name.clone(),
joints: joint_handles,
inverse_bind_matrices: inverse_bindposes_handle,
};
let handle = load_context
.add_labeled_asset(FbxAssetLabel::Skin(skin_index).to_string(), fbx_skin);
skins.push(handle.clone());
if !skin_name.starts_with("Skin_") {
named_skins.insert(Box::from(skin_name.as_str()), handle);
}
}
}
Ok((skins, named_skins))
}
+142
View File
@@ -0,0 +1,142 @@
//! Scene building functionality for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::loader::FbxLoaderSettings;
use crate::utils::convert_matrix;
use bevy::asset::{Handle, LoadContext};
use bevy::pbr::StandardMaterial;
use bevy::prelude::*;
use bevy::world_serialization::WorldAsset;
use std::collections::HashMap;
/// Build the final scene with all entities.
pub fn build_scene(
scene: &ufbx::Scene,
meshes: &[Handle<Mesh>],
materials: &[Handle<StandardMaterial>],
named_materials: &HashMap<Box<str>, Handle<StandardMaterial>>,
mesh_transforms: &[ufbx::Matrix],
mesh_material_info: &[Vec<String>],
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<Handle<WorldAsset>, FbxError> {
let mut world = World::new();
// Create default material if needed
let default_material = materials.get(0).cloned().unwrap_or_else(|| {
load_context.add_labeled_asset(
FbxAssetLabel::DefaultMaterial.to_string(),
StandardMaterial::default(),
)
});
// Spawn meshes
for (mesh_index, ((mesh_handle, transform_matrix), mat_names)) in meshes
.iter()
.zip(mesh_transforms.iter())
.zip(mesh_material_info.iter())
.enumerate()
{
let transform = Transform::from_matrix(convert_matrix(transform_matrix));
// Find material
let material = mat_names
.iter()
.find_map(|name| named_materials.get(name as &str))
.cloned()
.or_else(|| {
materials
.get(mesh_index.min(materials.len().saturating_sub(1)))
.cloned()
})
.unwrap_or_else(|| default_material.clone());
world.spawn((
Mesh3d(mesh_handle.clone()),
MeshMaterial3d(material),
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
// Spawn lights
if settings.load_lights {
spawn_lights(scene, &mut world);
}
let scene_handle =
load_context.add_labeled_asset(FbxAssetLabel::Scene(0).to_string(), WorldAsset::new(world));
Ok(scene_handle)
}
/// Spawn lights in the scene.
pub fn spawn_lights(scene: &ufbx::Scene, world: &mut World) {
for light in scene.lights.as_ref().iter() {
if let Some(light_node) = scene.nodes.as_ref().iter().find(|n| {
n.light.is_some()
&& n.light.as_ref().unwrap().element.element_id == light.element.element_id
}) {
let transform = Transform::from_matrix(convert_matrix(&light_node.node_to_world));
match light.type_ {
ufbx::LightType::Directional => {
world.spawn((
DirectionalLight {
color: Color::srgb(
light.color.x as f32,
light.color.y as f32,
light.color.z as f32,
),
illuminance: light.intensity as f32 * 10000.0,
shadow_maps_enabled: light.cast_shadows,
..Default::default()
},
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
ufbx::LightType::Point => {
world.spawn((
PointLight {
color: Color::srgb(
light.color.x as f32,
light.color.y as f32,
light.color.z as f32,
),
intensity: light.intensity as f32 * 1000.0,
shadow_maps_enabled: light.cast_shadows,
..Default::default()
},
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
ufbx::LightType::Spot => {
world.spawn((
SpotLight {
color: Color::srgb(
light.color.x as f32,
light.color.y as f32,
light.color.z as f32,
),
intensity: light.intensity as f32 * 1000.0,
shadow_maps_enabled: light.cast_shadows,
inner_angle: light.inner_angle as f32,
outer_angle: light.outer_angle as f32,
..Default::default()
},
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
_ => {}
}
}
}
}
+195
View File
@@ -0,0 +1,195 @@
//! Type definitions for the FBX loader.
use bevy::asset::{Asset, Handle};
use bevy::math::Affine2;
use bevy::pbr::StandardMaterial;
use bevy::prelude::*;
use bevy::mesh::skinning::SkinnedMeshInverseBindposes;
use bevy::world_serialization::WorldAsset;
use std::collections::HashMap;
// ============================================================================
// Coordinate System
// ============================================================================
/// Handedness of a coordinate system.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Handedness {
Right,
Left,
}
/// Coordinate axes definition.
#[derive(Debug, Clone, Copy)]
pub struct FbxAxisSystem {
pub up: Vec3,
pub front: Vec3,
pub handedness: Handedness,
}
// ============================================================================
// Metadata
// ============================================================================
/// Metadata from FBX header.
#[derive(Debug, Clone, Default)]
pub struct FbxMeta {
pub creator: Option<String>,
pub creation_time: Option<String>,
pub original_application: Option<String>,
}
// ============================================================================
// Textures and Materials
// ============================================================================
/// Texture wrapping modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxWrapMode {
Repeat,
Clamp,
}
/// Types of textures in FBX materials.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FbxTextureType {
BaseColor,
Normal,
Metallic,
Roughness,
Emission,
AmbientOcclusion,
Height,
}
/// Texture information.
#[derive(Debug, Clone)]
pub struct FbxTexture {
pub name: String,
pub filename: String,
pub absolute_filename: String,
pub uv_set: String,
pub uv_transform: Affine2,
pub wrap_u: FbxWrapMode,
pub wrap_v: FbxWrapMode,
}
/// Material representation.
#[derive(Debug, Clone)]
pub struct FbxMaterial {
pub name: String,
pub base_color: Color,
pub metallic: f32,
pub roughness: f32,
pub emission: Color,
pub normal_scale: f32,
pub alpha: f32,
pub alpha_cutoff: f32,
pub double_sided: bool,
pub textures: HashMap<FbxTextureType, FbxTexture>,
}
// ============================================================================
// Lights and Cameras
// ============================================================================
/// Light types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxLightType {
Directional,
Point,
Spot,
Area,
Volume,
}
/// Light definition.
#[derive(Debug, Clone)]
pub struct FbxLight {
pub name: String,
pub light_type: FbxLightType,
pub color: Color,
pub intensity: f32,
pub cast_shadows: bool,
pub inner_angle: Option<f32>,
pub outer_angle: Option<f32>,
}
/// Camera projection modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxProjectionMode {
Perspective,
Orthographic,
}
/// Camera definition.
#[derive(Debug, Clone)]
pub struct FbxCamera {
pub name: String,
pub projection_mode: FbxProjectionMode,
pub field_of_view_deg: f32,
pub aspect_ratio: f32,
pub near_plane: f32,
pub far_plane: f32,
pub focal_length_mm: f32,
}
// ============================================================================
// Scene Elements
// ============================================================================
/// FBX node with hierarchy.
#[derive(Asset, Debug, Clone, TypePath)]
pub struct FbxNode {
pub index: usize,
pub name: String,
pub children: Vec<Handle<FbxNode>>,
pub mesh: Option<Handle<Mesh>>,
pub skin: Option<Handle<FbxSkin>>,
pub transform: Transform,
pub visible: bool,
}
/// FBX skin for skeletal animation.
#[derive(Asset, Debug, Clone, TypePath)]
pub struct FbxSkin {
pub index: usize,
pub name: String,
pub joints: Vec<Handle<FbxNode>>,
pub inverse_bind_matrices: Handle<SkinnedMeshInverseBindposes>,
}
/// Placeholder for skeleton data.
#[derive(Asset, Debug, Clone, TypePath)]
pub struct Skeleton;
/// Animation interpolation modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxInterpolation {
Constant,
Linear,
Cubic,
}
// ============================================================================
// Main FBX Asset
// ============================================================================
/// Representation of a loaded FBX file.
#[derive(Asset, Debug, TypePath)]
pub struct Fbx {
pub scenes: Vec<Handle<WorldAsset>>,
pub named_scenes: HashMap<Box<str>, Handle<WorldAsset>>,
pub meshes: Vec<Handle<Mesh>>,
pub named_meshes: HashMap<Box<str>, Handle<Mesh>>,
pub materials: Vec<Handle<StandardMaterial>>,
pub named_materials: HashMap<Box<str>, Handle<StandardMaterial>>,
pub nodes: Vec<Handle<FbxNode>>,
pub named_nodes: HashMap<Box<str>, Handle<FbxNode>>,
pub skins: Vec<Handle<FbxSkin>>,
pub named_skins: HashMap<Box<str>, Handle<FbxSkin>>,
pub default_scene: Option<Handle<WorldAsset>>,
pub axis_system: FbxAxisSystem,
pub unit_scale: f32,
pub metadata: FbxMeta,
}
+58
View File
@@ -0,0 +1,58 @@
//! Utility functions for converting between ufbx and Bevy types.
use bevy::math::{Affine2, Mat4};
use bevy::prelude::*;
/// Convert ufbx texture UV transform to Bevy Affine2.
pub fn convert_texture_uv_transform(texture: &ufbx::Texture) -> Affine2 {
let translation = Vec2::new(
texture.uv_transform.translation.x as f32,
texture.uv_transform.translation.y as f32,
);
let scale = Vec2::new(
texture.uv_transform.scale.x as f32,
texture.uv_transform.scale.y as f32,
);
let rotation_z = texture.uv_transform.rotation.z as f32;
Affine2::from_scale_angle_translation(scale, rotation_z, translation)
}
/// Convert ufbx matrix to Bevy Mat4.
pub fn convert_matrix(m: &ufbx::Matrix) -> Mat4 {
Mat4::from_cols_array(&[
m.m00 as f32,
m.m10 as f32,
m.m20 as f32,
0.0,
m.m01 as f32,
m.m11 as f32,
m.m21 as f32,
0.0,
m.m02 as f32,
m.m12 as f32,
m.m22 as f32,
0.0,
m.m03 as f32,
m.m13 as f32,
m.m23 as f32,
1.0,
])
}
/// Convert ufbx transform to Bevy Transform.
pub fn convert_transform(t: &ufbx::Transform) -> Transform {
Transform {
translation: Vec3::new(
t.translation.x as f32,
t.translation.y as f32,
t.translation.z as f32,
),
rotation: Quat::from_xyzw(
t.rotation.x as f32,
t.rotation.y as f32,
t.rotation.z as f32,
t.rotation.w as f32,
),
scale: Vec3::new(t.scale.x as f32, t.scale.y as f32, t.scale.z as f32),
}
}