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
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ common_api = [
"bevy_gizmos_render",
"bevy_anti_alias",
"bevy_gltf",
"bevy_gltf_render",
"bevy_pbr",
"bevy_post_process",
"gltf_animation",
Expand Down Expand Up @@ -317,6 +318,9 @@ bevy_gilrs = ["bevy_internal/bevy_gilrs"]
# [glTF](https://www.khronos.org/gltf/) support
bevy_gltf = ["bevy_internal/bevy_gltf"]

# Renders GLTFs via PBR
bevy_gltf_render = ["bevy_internal/bevy_gltf_render"]

# Adds PBR rendering
bevy_pbr = ["bevy_internal/bevy_pbr"]

Expand Down
16 changes: 9 additions & 7 deletions crates/bevy_gltf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ license = "MIT OR Apache-2.0"
keywords = ["bevy"]

[features]
pbr_transmission_textures = ["bevy_pbr/pbr_transmission_textures"]
pbr_transmission_textures = ["bevy_material/pbr_transmission_textures"]
pbr_multi_layer_material_textures = [
"bevy_pbr/pbr_multi_layer_material_textures",
"bevy_material/pbr_multi_layer_material_textures",
]
pbr_anisotropy_texture = ["bevy_pbr/pbr_anisotropy_texture"]
pbr_specular_textures = ["bevy_pbr/pbr_specular_textures"]
pbr_anisotropy_texture = ["bevy_material/pbr_anisotropy_texture"]
pbr_specular_textures = ["bevy_material/pbr_specular_textures"]

[dependencies]
# bevy
Expand All @@ -29,10 +29,11 @@ bevy_image = { path = "../bevy_image", version = "0.18.0-dev" }
bevy_light = { path = "../bevy_light", version = "0.18.0-dev" }
bevy_camera = { path = "../bevy_camera", version = "0.18.0-dev" }
bevy_math = { path = "../bevy_math", version = "0.18.0-dev" }
bevy_mesh = { path = "../bevy_mesh", version = "0.18.0-dev" }
bevy_pbr = { path = "../bevy_pbr", version = "0.18.0-dev" }
bevy_mesh = { path = "../bevy_mesh", version = "0.18.0-dev", features = [
"morph",
"bevy_mikktspace",
] }
bevy_reflect = { path = "../bevy_reflect", version = "0.18.0-dev" }
bevy_render = { path = "../bevy_render", version = "0.18.0-dev" }
bevy_material = { path = "../bevy_material", version = "0.18.0-dev" }
bevy_scene = { path = "../bevy_scene", version = "0.18.0-dev" }
bevy_transform = { path = "../bevy_transform", version = "0.18.0-dev" }
Expand Down Expand Up @@ -65,6 +66,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.140"
smallvec = { version = "1", default-features = false }
tracing = { version = "0.1", default-features = false, features = ["std"] }
wgpu-types = { version = "26", default-features = false }

[dev-dependencies]
bevy_log = { path = "../bevy_log", version = "0.18.0-dev" }
Expand Down
38 changes: 38 additions & 0 deletions crates/bevy_gltf/render/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
[package]
name = "bevy_gltf_render"
version = "0.18.0-dev"
edition = "2024"
description = "Bevy Engine GLTF loading"
homepage = "https://bevy.org"
repository = "https://github.com/bevyengine/bevy"
license = "MIT OR Apache-2.0"
keywords = ["bevy"]

[features]
pbr_transmission_textures = ["bevy_material/pbr_transmission_textures"]
pbr_multi_layer_material_textures = [
"bevy_material/pbr_multi_layer_material_textures",
]
pbr_anisotropy_texture = ["bevy_material/pbr_anisotropy_texture"]
pbr_specular_textures = ["bevy_material/pbr_specular_textures"]

[dependencies]
# bevy
bevy_app = { path = "../../bevy_app", version = "0.18.0-dev" }
bevy_asset = { path = "../../bevy_asset", version = "0.18.0-dev" }
bevy_ecs = { path = "../../bevy_ecs", version = "0.18.0-dev" }
bevy_gltf = { path = "../", version = "0.18.0-dev" }
bevy_material = { path = "../../bevy_material", version = "0.18.0-dev" }
bevy_pbr = { path = "../../bevy_pbr", version = "0.18.0-dev" }

# other

[dev-dependencies]
bevy_log = { path = "../../bevy_log", version = "0.18.0-dev" }

[lints]
workspace = true

[package.metadata.docs.rs]
rustdoc-args = ["-Zunstable-options", "--generate-link-to-definition"]
all-features = true
176 changes: 176 additions & 0 deletions crates/bevy_gltf/render/LICENSE-APACHE
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS
19 changes: 19 additions & 0 deletions crates/bevy_gltf/render/LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
26 changes: 26 additions & 0 deletions crates/bevy_gltf/render/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]

//! Plugin for rendering GLTF's using PBR

use bevy_app::{App, Plugin, PreUpdate};


pub mod render;

pub use render::*;

#[derive(Default)]
pub struct GltfRenderPlugin;

impl Plugin for GltfRenderPlugin {
fn build(&self, app: &mut App) {
// TODO: set this schedule to just after the Marker gets added
app.add_systems(PreUpdate, swap_marker_mesh_material_3d);
}
}

76 changes: 76 additions & 0 deletions crates/bevy_gltf/render/src/render.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use bevy_asset::Assets;
use bevy_ecs::{
entity::Entity,
system::{Commands, Query, Res, ResMut},
};
use bevy_gltf::material::{MarkerMeshMaterial3d, GltfMaterial};
use bevy_pbr::{MeshMaterial3d, StandardMaterial};


fn material_from_short_material(material: &GltfMaterial) -> StandardMaterial {
StandardMaterial {
base_color: material.base_color,
base_color_channel: material.base_color_channel.clone(),
base_color_texture: material.base_color_texture.clone(),
emissive: material.emissive,
emissive_channel: material.emissive_channel.clone(),
emissive_texture: material.emissive_texture.clone(),
perceptual_roughness: material.perceptual_roughness,
metallic: material.metallic,
metallic_roughness_channel: material.metallic_roughness_channel.clone(),
metallic_roughness_texture: material.metallic_roughness_texture.clone(),
reflectance: material.reflectance,
specular_tint: material.specular_tint,
specular_transmission: material.specular_transmission,
#[cfg(feature = "pbr_transmission_textures")]
specular_transmission_channel: material.specular_transmission_channel.clone(),
#[cfg(feature = "pbr_transmission_textures")]
specular_transmission_texture: material.specular_transmission_texture.clone(),
thickness: material.thickness,
#[cfg(feature = "pbr_transmission_textures")]
thickness_channel: material.thickness_channel.clone(),
#[cfg(feature = "pbr_transmission_textures")]
thickness_texture: material.thickness_texture.clone(),
ior: material.ior,
attenuation_distance: material.attenuation_distance,
attenuation_color: material.attenuation_color,
normal_map_channel: material.normal_map_channel.clone(),
normal_map_texture: material.normal_map_texture.clone(),
occlusion_channel: material.occlusion_channel.clone(),
occlusion_texture: material.occlusion_texture.clone(),
clearcoat: material.clearcoat,
clearcoat_perceptual_roughness: material.clearcoat_perceptual_roughness,
anisotropy_strength: material.anisotropy_strength,
anisotropy_rotation: material.anisotropy_rotation,
double_sided: material.double_sided,
cull_mode: material.cull_mode,
unlit: material.unlit,
alpha_mode: material.alpha_mode,
uv_transform: material.uv_transform,
..Default::default()
}
}

pub(crate) fn swap_marker_mesh_material_3d(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will require an entry in the migration guides, etc for people who are spawning gltf and managing materials, since it will introduce a delay in the appearance of StandardMaterial for SceneInstanceReady users (they will lose access to the StandardMaterial and instead have to use GltfMaterial) and lifecycle observer users (who will not see an On<Add, StandardMaterial> until after the scene has spawned and this system has run).

Also that migration guide will have to clearly note that removing the MarkerMeshMaterial3d is critical, or bevy will overwrite their materials (or add additional second materials if a user applied a custom material) on the next frame.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's another issue - a new StandardMaterial is created for each instance of a mesh with that material. So a glTF with a hundred mesh instances all using same material will end up creating a hundred duplicate StandardMaterial assets.

I've sketched out a potential alternative below - this gives the renderer a way to translate materials during load_gltf so there's no need for post-spawn fixup. It also means the glTF loader can print an error if the renderer hasn't provided a translator or fails during translation.

Unfortunately it's kinda ugly. But maybe as the asset pipeline and scene systems mature it can become more generic - some kind of BSN patch or a BSN -> BSN transform. Also might become simpler if MeshMaterial3d gets changed to a type erased handle, so insert_material is no longer required.

In bevy_gltf:

// Utility for letting renderers translate `GltfMaterial` into their own material type. The renderer
// should add this as a resource during `Plugin::build`.
#[derive(Resource)]
struct GltfMaterialTranslator {
    // Create a material asset from a `GltfMaterial` and a label.
    load_material: Box<dyn Fn(&GltfMaterial, &GltfAssetLabel, &mut LoadContext) -> Result<UntypedHandle, BevyError>>,
    // Insert a material component using a label that was previously passed to `load_material`.
    insert_material: Box<dyn Fn(&GltfAssetLabel, &mut LoadContext, &EntityWorldMut)> -> Result<(), BevyError>>,
}

struct GltfLoader {
    ...
    material_translator: Option<GltfMaterialTranslator>,
}

fn load_material(..., material_translator: &Option<GltfMaterialTranslator>) {
    let gltf_material: GltfMaterial = ...;
    
    if let Some(material_translator) = material_translator {
        match material_translator.load_material(&gltf_material, &material_label, load_context) {
            Ok(handle) return handle;
            Err(err) { warn!("{err}"); return /* TODO? Does `load_material` return a Result?*/; }
        }
    }
}

fn load_node(..., material_translator: &Option<GltfMaterialTranslator>) {
    ...
    
    // Replaces where `MeshMaterial3d` is inserted into `mesh_entity`.
    if let Some(material_translator) = material_translator {
        if let Err(err) = material_translator.insert_material(&material_label, load_context, &mut mesh_entity) {
            warn!("{err}");
        }
    }
    
    ...
}

impl Plugin for GltfPlugin {
    fn finish(&self, app: &mut App) {
        ...
        
        // Copy the material translator resource into the loader. This means we can access it in `GltfLoader::load`,
        // which doesn't have access to world resources.
        let material_translator = app.world().get_resource<GltfMaterialTranslator>().cloned();
        
        if material_translator.is_none() {
            warn!("Missing material translator");
        }
        
        ...
        
        GltfLoader { ..., material_translator }
    }
}

In bevy_pbr:

impl Plugin for PbrPlugin {
    fn build(...) {
        ...
        
        let gltf_material_translator = GltfMaterialTranslator {
            load_material: |gltf_material, label, load_context| {
                Ok(load_context
                    .labeled_asset_scope::<_, ()>(label.to_string(), |load_context| {
                        ... create a StandardMaterial from the GltfMaterial ...
                    }).untyped())
            },
            insert_material: |label, load_context, entity| {
                let handle = load_context.get_label_handle::<StandardMaterial>()
                    .ok_or_else(|| "TODO: error".into())?;
                    
                entity.insert(MeshMaterial3d(handle))
                Ok(())
            },
        };
        
        app.insert_resource(gltf_material_translator);
    }
}

mut commands: Commands,
query: Query<(Entity, &MarkerMeshMaterial3d)>,
short_materials: Res<Assets<GltfMaterial>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for (entity, marker) in &query {
let content = &marker.0;

let short_material = short_materials.get(content).unwrap();

let material = material_from_short_material(short_material);

let content2 = materials.add(material);

let mesh_material_3d = MeshMaterial3d::<StandardMaterial>(content2);

commands
.entity(entity)
.remove::<MarkerMeshMaterial3d>()
.insert(mesh_material_3d);
}
}
Loading
Loading