Struct bevy::asset::AssetServer
source · pub struct AssetServer { /* private fields */ }
Expand description
Loads and tracks the state of Asset
values from a configured AssetReader
. This can be used to kick off new asset loads and
retrieve their current load states.
The general process to load an asset is:
- Initialize a new
Asset
type with theAssetServer
viaAssetApp::init_asset
, which will internally callAssetServer::register_asset
and set up related ECSAssets
storage and systems. - Register one or more
AssetLoader
s for that asset withAssetApp::init_asset_loader
- Add the asset to your asset folder (defaults to
assets
). - Call
AssetServer::load
with a path to your asset.
AssetServer
can be cloned. It is backed by an Arc
so clones will share state. Clones can be freely used in parallel.
Implementations§
source§impl AssetServer
impl AssetServer
sourcepub fn new(
sources: AssetSources,
mode: AssetServerMode,
watching_for_changes: bool,
) -> AssetServer
pub fn new( sources: AssetSources, mode: AssetServerMode, watching_for_changes: bool, ) -> AssetServer
Create a new instance of AssetServer
. If watch_for_changes
is true, the AssetReader
storage will watch for changes to
asset sources and hot-reload them.
sourcepub fn new_with_meta_check(
sources: AssetSources,
mode: AssetServerMode,
meta_check: AssetMetaCheck,
watching_for_changes: bool,
) -> AssetServer
pub fn new_with_meta_check( sources: AssetSources, mode: AssetServerMode, meta_check: AssetMetaCheck, watching_for_changes: bool, ) -> AssetServer
Create a new instance of AssetServer
. If watch_for_changes
is true, the AssetReader
storage will watch for changes to
asset sources and hot-reload them.
sourcepub fn get_source<'a>(
&'a self,
source: impl Into<AssetSourceId<'a>>,
) -> Result<&'a AssetSource, MissingAssetSourceError>
pub fn get_source<'a>( &'a self, source: impl Into<AssetSourceId<'a>>, ) -> Result<&'a AssetSource, MissingAssetSourceError>
Retrieves the AssetSource
for the given source
.
sourcepub fn watching_for_changes(&self) -> bool
pub fn watching_for_changes(&self) -> bool
Returns true if the AssetServer
watches for changes.
sourcepub fn register_loader<L>(&self, loader: L)where
L: AssetLoader,
pub fn register_loader<L>(&self, loader: L)where
L: AssetLoader,
Registers a new AssetLoader
. AssetLoader
s must be registered before they can be used.
sourcepub fn register_asset<A>(&self, assets: &Assets<A>)where
A: Asset,
pub fn register_asset<A>(&self, assets: &Assets<A>)where
A: Asset,
sourcepub async fn get_asset_loader_with_extension(
&self,
extension: &str,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
pub async fn get_asset_loader_with_extension( &self, extension: &str, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
Returns the registered AssetLoader
associated with the given extension, if it exists.
sourcepub async fn get_asset_loader_with_type_name(
&self,
type_name: &str,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeNameError>
pub async fn get_asset_loader_with_type_name( &self, type_name: &str, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeNameError>
Returns the registered AssetLoader
associated with the given std::any::type_name
, if it exists.
sourcepub async fn get_path_asset_loader<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
pub async fn get_path_asset_loader<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
Retrieves the default AssetLoader
for the given path, if one can be found.
sourcepub async fn get_asset_loader_with_asset_type_id<'a>(
&self,
type_id: TypeId,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>
pub async fn get_asset_loader_with_asset_type_id<'a>( &self, type_id: TypeId, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>
Retrieves the default AssetLoader
for the given Asset
TypeId
, if one can be found.
sourcepub async fn get_asset_loader_with_asset_type<'a, A>(
&self,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>where
A: Asset,
pub async fn get_asset_loader_with_asset_type<'a, A>(
&self,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>where
A: Asset,
Retrieves the default AssetLoader
for the given Asset
type, if one can be found.
sourcepub fn load<'a, A>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>where
A: Asset,
pub fn load<'a, A>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>where
A: Asset,
Begins loading an Asset
of type A
stored at path
. This will not block on the asset load. Instead,
it returns a “strong” Handle
. When the Asset
is loaded (and enters LoadState::Loaded
), it will be added to the
associated Assets
resource.
In case the file path contains a hashtag (#
), the path
must be specified using Path
or AssetPath
because otherwise the hashtag would be interpreted as separator between
the file path and the label. For example:
// `#path` is a label.
asset_server.load("some/file#path");
// `#path` is part of the file name.
asset_server.load(Path::new("some/file#path"));
Furthermore, if you need to load a file with a hashtag in its name and a label, you can
manually construct an AssetPath
.
asset_server.load(AssetPath::from_path(Path::new("some/file#path")).with_label("subasset"));
You can check the asset’s load state by reading AssetEvent
events, calling AssetServer::load_state
, or checking
the Assets
storage to see if the Asset
exists yet.
The asset load will fail and an error will be printed to the logs if the asset stored at path
is not of type A
.
Examples found in repository?
More examples
- examples/audio/audio_control.rs
- examples/3d/reflection_probes.rs
- examples/2d/sprite.rs
- examples/shader/custom_phase_item.rs
- examples/state/computed_states.rs
- examples/ecs/removal_detection.rs
- examples/2d/move_sprite.rs
- examples/3d/lightmaps.rs
- examples/asset/asset_decompression.rs
- examples/scene/scene.rs
- examples/3d/clearcoat.rs
- examples/2d/sprite_flipping.rs
- examples/asset/custom_asset.rs
- examples/asset/processing/asset_processing.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/2d/sprite_tile.rs
- examples/3d/color_grading.rs
- examples/3d/anisotropy.rs
- examples/audio/soundtrack.rs
- examples/ui/overflow_debug.rs
- examples/shader/shader_material_2d.rs
- examples/shader/array_texture.rs
- examples/3d/ssr.rs
- examples/2d/custom_gltf_vertex_attribute.rs
- examples/shader/shader_material.rs
- examples/shader/shader_material_glsl.rs
- examples/shader/texture_binding_array.rs
- examples/asset/extra_source.rs
- examples/2d/pixel_grid_snap.rs
- examples/2d/sprite_slice.rs
- examples/ecs/parallel_query.rs
- examples/asset/hot_asset_reloading.rs
- examples/ui/window_fallthrough.rs
- examples/2d/transparency_2d.rs
- examples/animation/morph_targets.rs
- examples/2d/sprite_sheet.rs
- examples/asset/embedded_asset.rs
- examples/3d/load_gltf_extras.rs
- examples/ui/font_atlas_debug.rs
- examples/3d/tonemapping.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/3d/animated_material.rs
- examples/stress_tests/text_pipeline.rs
- examples/games/loading_screen.rs
- examples/games/game_menu.rs
- examples/3d/skybox.rs
- examples/3d/depth_of_field.rs
- examples/3d/load_gltf.rs
- examples/3d/update_gltf_scene.rs
- examples/stress_tests/many_sprites.rs
- examples/3d/atmospheric_fog.rs
- examples/ecs/hierarchy.rs
- examples/2d/mesh2d_vertex_color_texture.rs
- examples/3d/volumetric_fog.rs
- examples/3d/generate_custom_mesh.rs
- examples/ui/button.rs
- examples/ui/relative_cursor_position.rs
- examples/animation/animation_graph.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/window/multiple_windows.rs
- examples/ui/ui_scaling.rs
- examples/2d/bloom_2d.rs
- examples/games/contributors.rs
- examples/2d/rotation.rs
- examples/ui/ui_texture_atlas.rs
- examples/audio/spatial_audio_2d.rs
- examples/stress_tests/many_buttons.rs
- examples/input/text_input.rs
- examples/2d/sprite_animation.rs
- examples/ui/ui_texture_slice.rs
- examples/audio/spatial_audio_3d.rs
- examples/3d/texture.rs
- examples/3d/visibility_range.rs
- examples/animation/animated_fox.rs
- examples/3d/motion_blur.rs
- examples/games/stepping.rs
- examples/ui/transparency_ui.rs
- examples/ui/size_constraints.rs
- examples/ui/ui_texture_atlas_slice.rs
- examples/transforms/align.rs
- examples/3d/anti_aliasing.rs
- examples/time/virtual_time.rs
- examples/games/alien_cake_addict.rs
- examples/asset/repeated_texture.rs
- examples/2d/mesh2d_arcs.rs
- examples/ui/text.rs
- examples/asset/asset_settings.rs
- examples/stress_tests/bevymark.rs
- examples/3d/meshlet.rs
- examples/ui/text_wrap_debug.rs
- examples/3d/pbr.rs
- examples/3d/auto_exposure.rs
- examples/asset/asset_loading.rs
- examples/shader/shader_prepass.rs
- examples/ui/flex_layout.rs
- examples/ui/overflow.rs
- examples/ui/display_and_visibility.rs
- examples/stress_tests/many_foxes.rs
- examples/games/breakout.rs
- examples/2d/texture_atlas.rs
- examples/2d/text2d.rs
- examples/3d/split_screen.rs
- examples/games/desk_toy.rs
- examples/3d/parallax_mapping.rs
- examples/ui/text_debug.rs
- examples/3d/deferred_rendering.rs
- examples/3d/blend_modes.rs
- examples/3d/lighting.rs
- examples/ui/grid.rs
- examples/3d/transmission.rs
- examples/ui/ui.rs
sourcepub fn load_acquire<'a, A, G>(
&self,
path: impl Into<AssetPath<'a>>,
guard: G,
) -> Handle<A>
pub fn load_acquire<'a, A, G>( &self, path: impl Into<AssetPath<'a>>, guard: G, ) -> Handle<A>
Begins loading an Asset
of type A
stored at path
while holding a guard item.
The guard item is dropped when either the asset is loaded or loading has failed.
This function returns a “strong” Handle
. When the Asset
is loaded (and enters LoadState::Loaded
), it will be added to the
associated Assets
resource.
The guard item should notify the caller in its Drop
implementation. See example multi_asset_sync
.
Synchronously this can be a Arc<AtomicU32>
that decrements its counter, asynchronously this can be a Barrier
.
This function only guarantees the asset referenced by the Handle
is loaded. If your asset is separated into
multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the AssetLoader
.
Additionally, you can check the asset’s load state by reading AssetEvent
events, calling AssetServer::load_state
, or checking
the Assets
storage to see if the Asset
exists yet.
The asset load will fail and an error will be printed to the logs if the asset stored at path
is not of type A
.
Examples found in repository?
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
fn setup_assets(mut commands: Commands, asset_server: Res<AssetServer>) {
let (barrier, guard) = AssetBarrier::new();
commands.insert_resource(OneHundredThings(std::array::from_fn(|i| match i % 5 {
0 => asset_server.load_acquire("models/GolfBall/GolfBall.glb", guard.clone()),
1 => asset_server.load_acquire("models/AlienCake/alien.glb", guard.clone()),
2 => asset_server.load_acquire("models/AlienCake/cakeBirthday.glb", guard.clone()),
3 => asset_server.load_acquire("models/FlightHelmet/FlightHelmet.gltf", guard.clone()),
4 => asset_server.load_acquire("models/torus/torus.gltf", guard.clone()),
_ => unreachable!(),
})));
let future = barrier.wait_async();
commands.insert_resource(barrier);
let loading_state = Arc::new(AtomicBool::new(false));
commands.insert_resource(AsyncLoadingState(loading_state.clone()));
// await the `AssetBarrierFuture`.
AsyncComputeTaskPool::get()
.spawn(async move {
future.await;
// Notify via `AsyncLoadingState`
loading_state.store(true, Ordering::Release);
})
.detach();
}
sourcepub fn load_with_settings<'a, A, S>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Handle<A>
pub fn load_with_settings<'a, A, S>( &self, path: impl Into<AssetPath<'a>>, settings: impl Fn(&mut S) + Send + Sync + 'static, ) -> Handle<A>
Begins loading an Asset
of type A
stored at path
. The given settings
function will override the asset’s
AssetLoader
settings. The type S
must match the configured AssetLoader::Settings
or settings
changes
will be ignored and an error will be printed to the log.
Examples found in repository?
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
fn spawn_car_paint_sphere(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
asset_server: &AssetServer,
sphere: &Handle<Mesh>,
) {
commands
.spawn(PbrBundle {
mesh: sphere.clone(),
material: materials.add(StandardMaterial {
clearcoat: 1.0,
clearcoat_perceptual_roughness: 0.1,
normal_map_texture: Some(asset_server.load_with_settings(
"textures/BlueNoise-Normal.png",
|settings: &mut ImageLoaderSettings| settings.is_srgb = false,
)),
metallic: 0.9,
perceptual_roughness: 0.5,
base_color: BLUE.into(),
..default()
}),
transform: Transform::from_xyz(-1.0, 1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
..default()
})
.insert(ExampleSphere);
}
/// Spawn a semitransparent object with a clearcoat layer.
fn spawn_coated_glass_bubble_sphere(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
sphere: &Handle<Mesh>,
) {
commands
.spawn(PbrBundle {
mesh: sphere.clone(),
material: materials.add(StandardMaterial {
clearcoat: 1.0,
clearcoat_perceptual_roughness: 0.1,
metallic: 0.5,
perceptual_roughness: 0.1,
base_color: Color::srgba(0.9, 0.9, 0.9, 0.3),
alpha_mode: AlphaMode::Blend,
..default()
}),
transform: Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
..default()
})
.insert(ExampleSphere);
}
/// Spawns an object with both a clearcoat normal map (a scratched varnish) and
/// a main layer normal map (the golf ball pattern).
///
/// This object is in glTF format, using the `KHR_materials_clearcoat`
/// extension.
fn spawn_golf_ball(commands: &mut Commands, asset_server: &AssetServer) {
commands
.spawn(SceneBundle {
scene: asset_server
.load(GltfAssetLabel::Scene(0).from_asset("models/GolfBall/GolfBall.glb")),
transform: Transform::from_xyz(1.0, 1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
..default()
})
.insert(ExampleSphere);
}
/// Spawns an object with only a clearcoat normal map (a scratch pattern) and no
/// main layer normal map.
fn spawn_scratched_gold_ball(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
asset_server: &AssetServer,
sphere: &Handle<Mesh>,
) {
commands
.spawn(PbrBundle {
mesh: sphere.clone(),
material: materials.add(StandardMaterial {
clearcoat: 1.0,
clearcoat_perceptual_roughness: 0.3,
clearcoat_normal_texture: Some(asset_server.load_with_settings(
"textures/ScratchedGold-Normal.png",
|settings: &mut ImageLoaderSettings| settings.is_srgb = false,
)),
metallic: 0.9,
perceptual_roughness: 0.1,
base_color: GOLD.into(),
..default()
}),
transform: Transform::from_xyz(1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
..default()
})
.insert(ExampleSphere);
}
More examples
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
fn setup_parallax(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
asset_server: Res<AssetServer>,
) {
// The normal map. Note that to generate it in the GIMP image editor, you should
// open the depth map, and do Filters → Generic → Normal Map
// You should enable the "flip X" checkbox.
let normal_handle = asset_server.load_with_settings(
"textures/parallax_example/cube_normal.png",
// The normal map texture is in linear color space. Lighting won't look correct
// if `is_srgb` is `true`, which is the default.
|settings: &mut ImageLoaderSettings| settings.is_srgb = false,
);
let mut cube = Mesh::from(Cuboid::new(0.15, 0.15, 0.15));
// NOTE: for normal maps and depth maps to work, the mesh
// needs tangents generated.
cube.generate_tangents().unwrap();
let parallax_material = materials.add(StandardMaterial {
perceptual_roughness: 0.4,
base_color_texture: Some(asset_server.load("textures/parallax_example/cube_color.png")),
normal_map_texture: Some(normal_handle),
// The depth map is a greyscale texture where black is the highest level and
// white the lowest.
depth_map: Some(asset_server.load("textures/parallax_example/cube_depth.png")),
parallax_depth_scale: 0.09,
parallax_mapping_method: ParallaxMappingMethod::Relief { max_steps: 4 },
max_parallax_layer_count: 5.0f32.exp2(),
..default()
});
commands.spawn((
PbrBundle {
mesh: meshes.add(cube),
material: parallax_material,
transform: Transform::from_xyz(0.4, 0.2, -0.8),
..default()
},
Spin { speed: 0.3 },
));
}
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
fn spawn_water(
commands: &mut Commands,
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
water_materials: &mut Assets<ExtendedMaterial<StandardMaterial, Water>>,
) {
commands.spawn(MaterialMeshBundle {
mesh: meshes.add(Plane3d::new(Vec3::Y, Vec2::splat(1.0))),
material: water_materials.add(ExtendedMaterial {
base: StandardMaterial {
base_color: BLACK.into(),
perceptual_roughness: 0.0,
..default()
},
extension: Water {
normals: asset_server.load_with_settings::<Image, ImageLoaderSettings>(
"textures/water_normals.png",
|settings| {
settings.is_srgb = false;
settings.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor {
address_mode_u: ImageAddressMode::Repeat,
address_mode_v: ImageAddressMode::Repeat,
mag_filter: ImageFilterMode::Linear,
min_filter: ImageFilterMode::Linear,
..default()
});
},
),
// These water settings are just random values to create some
// variety.
settings: WaterSettings {
octave_vectors: [
vec4(0.080, 0.059, 0.073, -0.062),
vec4(0.153, 0.138, -0.149, -0.195),
],
octave_scales: vec4(1.0, 2.1, 7.9, 14.9) * 5.0,
octave_strengths: vec4(0.16, 0.18, 0.093, 0.044),
},
},
}),
transform: Transform::from_scale(Vec3::splat(100.0)),
..default()
});
}
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let image_with_default_sampler =
asset_server.load("textures/fantasy_ui_borders/panel-border-010.png");
// central cube with not repeated texture
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
material: materials.add(StandardMaterial {
base_color_texture: Some(image_with_default_sampler.clone()),
..default()
}),
transform: Transform::from_translation(Vec3::ZERO),
..default()
});
// left cube with repeated texture
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
material: materials.add(StandardMaterial {
base_color_texture: Some(asset_server.load_with_settings(
"textures/fantasy_ui_borders/panel-border-010-repeated.png",
|s: &mut _| {
*s = ImageLoaderSettings {
sampler: ImageSampler::Descriptor(ImageSamplerDescriptor {
// rewriting mode to repeat image,
address_mode_u: ImageAddressMode::Repeat,
address_mode_v: ImageAddressMode::Repeat,
..default()
}),
..default()
}
},
)),
// uv_transform used here for proportions only, but it is full Affine2
// that's why you can use rotation and shift also
uv_transform: Affine2::from_scale(Vec2::new(2., 3.)),
..default()
}),
transform: Transform::from_xyz(-1.5, 0.0, 0.0),
..default()
});
// right cube with scaled texture, because with default sampler
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
material: materials.add(StandardMaterial {
// there is no sampler set, that's why
// by default you see only one small image in a row/column
// and other space is filled by image edge
base_color_texture: Some(image_with_default_sampler),
// uv_transform used here for proportions only, but it is full Affine2
// that's why you can use rotation and shift also
uv_transform: Affine2::from_scale(Vec2::new(2., 3.)),
..default()
}),
transform: Transform::from_xyz(1.5, 0.0, 0.0),
..default()
});
// light
commands.spawn(PointLightBundle {
point_light: PointLight {
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(4.0, 8.0, 4.0),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 1.5, 4.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Without any .meta file specifying settings, the default sampler [ImagePlugin::default()] is used for loading images.
// If you are using a very small image and rendering it larger like seen here, the default linear filtering will result in a blurry image.
// Useful note: The default sampler specified by the ImagePlugin is *not* the same as the default implementation of sampler. This is why
// everything uses linear by default but if you look at the default of sampler, it uses nearest.
commands.spawn(SpriteBundle {
texture: asset_server.load("bevy_pixel_dark.png"),
sprite: Sprite {
custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
..Default::default()
},
transform: Transform::from_xyz(-100.0, 0.0, 0.0),
..Default::default()
});
// When a .meta file is added with the same name as the asset and a '.meta' extension
// you can (and must) specify all fields of the asset loader's settings for that
// particular asset, in this case [ImageLoaderSettings]. Take a look at
// examples/asset/files/bevy_pixel_dark_with_meta.png.meta
// for the format and you'll notice, the only non-default option is setting Nearest
// filtering. This tends to work much better for pixel art assets.
// A good reference when filling this out is to check out [ImageLoaderSettings::default()]
// and follow to the default implementation of each fields type.
// https://docs.rs/bevy/latest/bevy/render/texture/struct.ImageLoaderSettings.html#
commands.spawn(SpriteBundle {
texture: asset_server.load("bevy_pixel_dark_with_meta.png"),
sprite: Sprite {
custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
..Default::default()
},
transform: Transform::from_xyz(100.0, 0.0, 0.0),
..Default::default()
});
// Another option is to use the AssetServers load_with_settings function.
// With this you can specify the same settings upon loading your asset with a
// couple of differences. A big one is that you aren't required to set *every*
// setting, just modify the ones that you need. It works by passing in a function
// (in this case an anonymous closure) that takes a reference to the settings type
// that is then modified in the function.
// Do note that if you want to load the same asset with different settings, the
// settings changes from any loads after the first of the same asset will be ignored.
// This is why this one loads a differently named copy of the asset instead of using
// same one as without a .meta file.
commands.spawn(SpriteBundle {
texture: asset_server.load_with_settings(
"bevy_pixel_dark_with_settings.png",
|settings: &mut ImageLoaderSettings| {
settings.sampler = ImageSampler::nearest();
},
),
sprite: Sprite {
custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
..Default::default()
},
transform: Transform::from_xyz(0.0, 150.0, 0.0),
..Default::default()
});
commands.spawn(Camera2dBundle::default());
}
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
fn setup(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
asset_server: Res<AssetServer>,
) {
// The normal map. Note that to generate it in the GIMP image editor, you should
// open the depth map, and do Filters → Generic → Normal Map
// You should enable the "flip X" checkbox.
let normal_handle = asset_server.load_with_settings(
"textures/parallax_example/cube_normal.png",
// The normal map texture is in linear color space. Lighting won't look correct
// if `is_srgb` is `true`, which is the default.
|settings: &mut ImageLoaderSettings| settings.is_srgb = false,
);
// Camera
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(1.5, 1.5, 1.5).looking_at(Vec3::ZERO, Vec3::Y),
..default()
},
CameraController,
));
// light
commands
.spawn(PointLightBundle {
transform: Transform::from_xyz(2.0, 1.0, -1.1),
point_light: PointLight {
shadows_enabled: true,
..default()
},
..default()
})
.with_children(|commands| {
// represent the light source as a sphere
let mesh = meshes.add(Sphere::new(0.05).mesh().ico(3).unwrap());
commands.spawn(PbrBundle { mesh, ..default() });
});
// Plane
commands.spawn(PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(10.0, 10.0)),
material: materials.add(StandardMaterial {
// standard material derived from dark green, but
// with roughness and reflectance set.
perceptual_roughness: 0.45,
reflectance: 0.18,
..Color::srgb_u8(0, 80, 0).into()
}),
transform: Transform::from_xyz(0.0, -1.0, 0.0),
..default()
});
let parallax_depth_scale = TargetDepth::default().0;
let max_parallax_layer_count = TargetLayers::default().0.exp2();
let parallax_mapping_method = CurrentMethod::default();
let parallax_material = materials.add(StandardMaterial {
perceptual_roughness: 0.4,
base_color_texture: Some(asset_server.load("textures/parallax_example/cube_color.png")),
normal_map_texture: Some(normal_handle),
// The depth map is a greyscale texture where black is the highest level and
// white the lowest.
depth_map: Some(asset_server.load("textures/parallax_example/cube_depth.png")),
parallax_depth_scale,
parallax_mapping_method: parallax_mapping_method.0,
max_parallax_layer_count,
..default()
});
commands.spawn((
PbrBundle {
mesh: meshes.add(
// NOTE: for normal maps and depth maps to work, the mesh
// needs tangents generated.
Mesh::from(Cuboid::default())
.with_generated_tangents()
.unwrap(),
),
material: parallax_material.clone_weak(),
..default()
},
Spin { speed: 0.3 },
));
let background_cube = meshes.add(
Mesh::from(Cuboid::new(40.0, 40.0, 40.0))
.with_generated_tangents()
.unwrap(),
);
let background_cube_bundle = |translation| {
(
PbrBundle {
transform: Transform::from_translation(translation),
mesh: background_cube.clone(),
material: parallax_material.clone(),
..default()
},
Spin { speed: -0.1 },
)
};
commands.spawn(background_cube_bundle(Vec3::new(45., 0., 0.)));
commands.spawn(background_cube_bundle(Vec3::new(-45., 0., 0.)));
commands.spawn(background_cube_bundle(Vec3::new(0., 0., 45.)));
commands.spawn(background_cube_bundle(Vec3::new(0., 0., -45.)));
let style = TextStyle::default();
// example instructions
commands.spawn(
TextBundle::from_sections(vec![
TextSection::new(
format!("Parallax depth scale: {parallax_depth_scale:.5}\n"),
style.clone(),
),
TextSection::new(
format!("Layers: {max_parallax_layer_count:.0}\n"),
style.clone(),
),
TextSection::new(format!("{parallax_mapping_method}\n"), style.clone()),
TextSection::new("\n\n", style.clone()),
TextSection::new("Controls:\n", style.clone()),
TextSection::new("Left click - Change view angle\n", style.clone()),
TextSection::new(
"1/2 - Decrease/Increase parallax depth scale\n",
style.clone(),
),
TextSection::new("3/4 - Decrease/Increase layer count\n", style.clone()),
TextSection::new("Space - Switch parallaxing algorithm\n", style),
])
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
}),
);
}
sourcepub fn load_acquire_with_settings<'a, A, S, G>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
guard: G,
) -> Handle<A>
pub fn load_acquire_with_settings<'a, A, S, G>( &self, path: impl Into<AssetPath<'a>>, settings: impl Fn(&mut S) + Send + Sync + 'static, guard: G, ) -> Handle<A>
Begins loading an Asset
of type A
stored at path
while holding a guard item.
The guard item is dropped when either the asset is loaded or loading has failed.
This function only guarantees the asset referenced by the Handle
is loaded. If your asset is separated into
multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the AssetLoader
.
The given settings
function will override the asset’s
AssetLoader
settings. The type S
must match the configured AssetLoader::Settings
or settings
changes
will be ignored and an error will be printed to the log.
sourcepub async fn load_untyped_async<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Result<UntypedHandle, AssetLoadError>
pub async fn load_untyped_async<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Result<UntypedHandle, AssetLoadError>
Asynchronously load an asset that you do not know the type of statically. If you do know the type of the asset,
you should use AssetServer::load
. If you don’t know the type of the asset, but you can’t use an async method,
consider using AssetServer::load_untyped
.
sourcepub fn load_untyped<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Handle<LoadedUntypedAsset>
pub fn load_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Handle<LoadedUntypedAsset>
Load an asset without knowing its type. The method returns a handle to a LoadedUntypedAsset
.
Once the LoadedUntypedAsset
is loaded, an untyped handle for the requested path can be
retrieved from it.
use bevy_asset::{Assets, Handle, LoadedUntypedAsset};
use bevy_ecs::system::{Res, Resource};
#[derive(Resource)]
struct LoadingUntypedHandle(Handle<LoadedUntypedAsset>);
fn resolve_loaded_untyped_handle(loading_handle: Res<LoadingUntypedHandle>, loaded_untyped_assets: Res<Assets<LoadedUntypedAsset>>) {
if let Some(loaded_untyped_asset) = loaded_untyped_assets.get(&loading_handle.0) {
let handle = loaded_untyped_asset.handle.clone();
// continue working with `handle` which points to the asset at the originally requested path
}
}
This indirection enables a non blocking load of an untyped asset, since I/O is required to figure out the asset type before a handle can be created.
sourcepub fn reload<'a>(&self, path: impl Into<AssetPath<'a>>)
pub fn reload<'a>(&self, path: impl Into<AssetPath<'a>>)
Kicks off a reload of the asset stored at the given path. This will only reload the asset if it currently loaded.
sourcepub fn add<A>(&self, asset: A) -> Handle<A>where
A: Asset,
pub fn add<A>(&self, asset: A) -> Handle<A>where
A: Asset,
Queues a new asset to be tracked by the AssetServer
and returns a Handle
to it. This can be used to track
dependencies of assets created at runtime.
After the asset has been fully loaded by the AssetServer
, it will show up in the relevant Assets
storage.
Examples found in repository?
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
fn decompress<A: Asset>(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut compressed_assets: ResMut<Assets<GzAsset>>,
query: Query<(Entity, &Compressed<A>)>,
) {
for (entity, Compressed { compressed, .. }) in query.iter() {
let Some(GzAsset { uncompressed }) = compressed_assets.remove(compressed) else {
continue;
};
let uncompressed = uncompressed.take::<A>().unwrap();
commands
.entity(entity)
.remove::<Compressed<A>>()
.insert(asset_server.add(uncompressed));
}
}
sourcepub fn add_async<A, E>(
&self,
future: impl Future<Output = Result<A, E>> + Send + 'static,
) -> Handle<A>
pub fn add_async<A, E>( &self, future: impl Future<Output = Result<A, E>> + Send + 'static, ) -> Handle<A>
Queues a new asset to be tracked by the AssetServer
and returns a Handle
to it. This can be used to track
dependencies of assets created at runtime.
After the asset has been fully loaded, it will show up in the relevant Assets
storage.
sourcepub fn load_folder<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Handle<LoadedFolder>
pub fn load_folder<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Handle<LoadedFolder>
Loads all assets from the specified folder recursively. The LoadedFolder
asset (when it loads) will
contain handles to all assets in the folder. You can wait for all assets to load by checking the LoadedFolder
’s
RecursiveDependencyLoadState
.
Loading the same folder multiple times will return the same handle. If the file_watcher
feature is enabled, LoadedFolder
handles will reload when a file in the folder is
removed, added or moved. This includes files in subdirectories and moving, adding,
or removing complete subdirectories.
Examples found in repository?
More examples
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
meshes: Res<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// By default AssetServer will load assets from inside the "assets" folder.
// For example, the next line will load GltfAssetLabel::Primitive{mesh:0,primitive:0}.from_asset("ROOT/assets/models/cube/cube.gltf"),
// where "ROOT" is the directory of the Application.
//
// This can be overridden by setting the "CARGO_MANIFEST_DIR" environment variable (see
// https://doc.rust-lang.org/cargo/reference/environment-variables.html)
// to another directory. When the Application is run through Cargo, "CARGO_MANIFEST_DIR" is
// automatically set to your crate (workspace) root directory.
let cube_handle = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset("models/cube/cube.gltf"),
);
let sphere_handle = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset("models/sphere/sphere.gltf"),
);
// All assets end up in their Assets<T> collection once they are done loading:
if let Some(sphere) = meshes.get(&sphere_handle) {
// You might notice that this doesn't run! This is because assets load in parallel without
// blocking. When an asset has loaded, it will appear in relevant Assets<T>
// collection.
info!("{:?}", sphere.primitive_topology());
} else {
info!("sphere hasn't loaded yet");
}
// You can load all assets in a folder like this. They will be loaded in parallel without
// blocking. The LoadedFolder asset holds handles to each asset in the folder. These are all
// dependencies of the LoadedFolder asset, meaning you can wait for the LoadedFolder asset to
// fire AssetEvent::LoadedWithDependencies if you want to wait for all assets in the folder
// to load.
// If you want to keep the assets in the folder alive, make sure you store the returned handle
// somewhere.
let _loaded_folder: Handle<LoadedFolder> = asset_server.load_folder("models/torus");
// If you want a handle to a specific asset in a loaded folder, the easiest way to get one is to call load.
// It will _not_ be loaded a second time.
// The LoadedFolder asset will ultimately also hold handles to the assets, but waiting for it to load
// and finding the right handle is more work!
let torus_handle = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset("models/torus/torus.gltf"),
);
// You can also add assets directly to their Assets<T> storage:
let material_handle = materials.add(StandardMaterial {
base_color: Color::srgb(0.8, 0.7, 0.6),
..default()
});
// torus
commands.spawn(PbrBundle {
mesh: torus_handle,
material: material_handle.clone(),
transform: Transform::from_xyz(-3.0, 0.0, 0.0),
..default()
});
// cube
commands.spawn(PbrBundle {
mesh: cube_handle,
material: material_handle.clone(),
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..default()
});
// sphere
commands.spawn(PbrBundle {
mesh: sphere_handle,
material: material_handle,
transform: Transform::from_xyz(3.0, 0.0, 0.0),
..default()
});
// light
commands.spawn(PointLightBundle {
transform: Transform::from_xyz(4.0, 5.0, 4.0),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 3.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
sourcepub fn get_load_states(
&self,
id: impl Into<UntypedAssetId>,
) -> Option<(LoadState, DependencyLoadState, RecursiveDependencyLoadState)>
pub fn get_load_states( &self, id: impl Into<UntypedAssetId>, ) -> Option<(LoadState, DependencyLoadState, RecursiveDependencyLoadState)>
Retrieves all loads states for the given asset id.
Examples found in repository?
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
fn update_loading_data(
mut loading_data: ResMut<LoadingData>,
mut loading_state: ResMut<LoadingState>,
asset_server: Res<AssetServer>,
pipelines_ready: Res<PipelinesReady>,
) {
if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
// If we are still loading assets / pipelines are not fully compiled,
// we reset the confirmation frame count.
loading_data.confirmation_frames_count = 0;
// Go through each asset and verify their load states.
// Any assets that are loaded are then added to the pop list for later removal.
let mut pop_list: Vec<usize> = Vec::new();
for (index, asset) in loading_data.loading_assets.iter().enumerate() {
if let Some(state) = asset_server.get_load_states(asset) {
if let bevy::asset::RecursiveDependencyLoadState::Loaded = state.2 {
pop_list.push(index);
}
}
}
// Remove all loaded assets from the loading_assets list.
for i in pop_list.iter() {
loading_data.loading_assets.remove(*i);
}
// If there are no more assets being monitored, and pipelines
// are compiled, then start counting confirmation frames.
// Once enough confirmations have passed, everything will be
// considered to be fully loaded.
} else {
loading_data.confirmation_frames_count += 1;
if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
*loading_state = LoadingState::LevelReady;
}
}
}
sourcepub fn get_load_state(&self, id: impl Into<UntypedAssetId>) -> Option<LoadState>
pub fn get_load_state(&self, id: impl Into<UntypedAssetId>) -> Option<LoadState>
Retrieves the main LoadState
of a given asset id
.
Note that this is “just” the root asset load state. To check if an asset and its recursive
dependencies have loaded, see AssetServer::is_loaded_with_dependencies
.
sourcepub fn get_recursive_dependency_load_state(
&self,
id: impl Into<UntypedAssetId>,
) -> Option<RecursiveDependencyLoadState>
pub fn get_recursive_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> Option<RecursiveDependencyLoadState>
Retrieves the RecursiveDependencyLoadState
of a given asset id
.
sourcepub fn load_state(&self, id: impl Into<UntypedAssetId>) -> LoadState
pub fn load_state(&self, id: impl Into<UntypedAssetId>) -> LoadState
Retrieves the main LoadState
of a given asset id
.
Examples found in repository?
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
fn environment_map_load_finish(
mut commands: Commands,
asset_server: Res<AssetServer>,
environment_maps: Query<&EnvironmentMapLight>,
label_query: Query<Entity, With<EnvironmentMapLabel>>,
) {
if let Ok(environment_map) = environment_maps.get_single() {
if asset_server.load_state(&environment_map.diffuse_map) == LoadState::Loaded
&& asset_server.load_state(&environment_map.specular_map) == LoadState::Loaded
{
if let Ok(label_entity) = label_query.get_single() {
commands.entity(label_entity).despawn();
}
}
}
}
More examples
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
fn asset_loaded(
asset_server: Res<AssetServer>,
mut images: ResMut<Assets<Image>>,
mut cubemap: ResMut<Cubemap>,
mut skyboxes: Query<&mut Skybox>,
) {
if !cubemap.is_loaded && asset_server.load_state(&cubemap.image_handle) == LoadState::Loaded {
info!("Swapping to {}...", CUBEMAPS[cubemap.index].0);
let image = images.get_mut(&cubemap.image_handle).unwrap();
// NOTE: PNGs do not have any metadata that could indicate they contain a cubemap texture,
// so they appear as one texture. The following code reconfigures the texture as necessary.
if image.texture_descriptor.array_layer_count() == 1 {
image.reinterpret_stacked_2d_as_array(image.height() / image.width());
image.texture_view_descriptor = Some(TextureViewDescriptor {
dimension: Some(TextureViewDimension::Cube),
..default()
});
}
for mut skybox in &mut skyboxes {
skybox.image = cubemap.image_handle.clone();
}
cubemap.is_loaded = true;
}
}
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
fn create_array_texture(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut loading_texture: ResMut<LoadingTexture>,
mut images: ResMut<Assets<Image>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ArrayTextureMaterial>>,
) {
if loading_texture.is_loaded
|| asset_server.load_state(loading_texture.handle.id()) != LoadState::Loaded
{
return;
}
loading_texture.is_loaded = true;
let image = images.get_mut(&loading_texture.handle).unwrap();
// Create a new array texture asset from the loaded texture.
let array_layers = 4;
image.reinterpret_stacked_2d_as_array(array_layers);
// Spawn some cubes using the array texture
let mesh_handle = meshes.add(Cuboid::default());
let material_handle = materials.add(ArrayTextureMaterial {
array_texture: loading_texture.handle.clone(),
});
for x in -5..=5 {
commands.spawn(MaterialMeshBundle {
mesh: mesh_handle.clone(),
material: material_handle.clone(),
transform: Transform::from_xyz(x as f32 + 0.5, 0.0, 0.0),
..Default::default()
});
}
}
sourcepub fn recursive_dependency_load_state(
&self,
id: impl Into<UntypedAssetId>,
) -> RecursiveDependencyLoadState
pub fn recursive_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> RecursiveDependencyLoadState
Retrieves the RecursiveDependencyLoadState
of a given asset id
.
sourcepub fn is_loaded_with_dependencies(&self, id: impl Into<UntypedAssetId>) -> bool
pub fn is_loaded_with_dependencies(&self, id: impl Into<UntypedAssetId>) -> bool
Returns true if the asset and all of its dependencies (recursive) have been loaded.
sourcepub fn get_handle<'a, A>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<Handle<A>>where
A: Asset,
pub fn get_handle<'a, A>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<Handle<A>>where
A: Asset,
Returns an active handle for the given path, if the asset at the given path has already started loading, or is still “alive”.
Examples found in repository?
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
fn setup(
mut commands: Commands,
rpg_sprite_handles: Res<RpgSpriteFolder>,
asset_server: Res<AssetServer>,
mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
loaded_folders: Res<Assets<LoadedFolder>>,
mut textures: ResMut<Assets<Image>>,
) {
let loaded_folder = loaded_folders.get(&rpg_sprite_handles.0).unwrap();
// create texture atlases with different padding and sampling
let (texture_atlas_linear, linear_texture) = create_texture_atlas(
loaded_folder,
None,
Some(ImageSampler::linear()),
&mut textures,
);
let atlas_linear_handle = texture_atlases.add(texture_atlas_linear.clone());
let (texture_atlas_nearest, nearest_texture) = create_texture_atlas(
loaded_folder,
None,
Some(ImageSampler::nearest()),
&mut textures,
);
let atlas_nearest_handle = texture_atlases.add(texture_atlas_nearest);
let (texture_atlas_linear_padded, linear_padded_texture) = create_texture_atlas(
loaded_folder,
Some(UVec2::new(6, 6)),
Some(ImageSampler::linear()),
&mut textures,
);
let atlas_linear_padded_handle = texture_atlases.add(texture_atlas_linear_padded.clone());
let (texture_atlas_nearest_padded, nearest_padded_texture) = create_texture_atlas(
loaded_folder,
Some(UVec2::new(6, 6)),
Some(ImageSampler::nearest()),
&mut textures,
);
let atlas_nearest_padded_handle = texture_atlases.add(texture_atlas_nearest_padded);
// setup 2d scene
commands.spawn(Camera2dBundle::default());
// padded textures are to the right, unpadded to the left
// draw unpadded texture atlas
commands.spawn(SpriteBundle {
texture: linear_texture.clone(),
transform: Transform {
translation: Vec3::new(-250.0, -130.0, 0.0),
scale: Vec3::splat(0.8),
..default()
},
..default()
});
// draw padded texture atlas
commands.spawn(SpriteBundle {
texture: linear_padded_texture.clone(),
transform: Transform {
translation: Vec3::new(250.0, -130.0, 0.0),
scale: Vec3::splat(0.8),
..default()
},
..default()
});
let font = asset_server.load("fonts/FiraSans-Bold.ttf");
// padding label text style
let text_style: TextStyle = TextStyle {
font: font.clone(),
font_size: 50.0,
..default()
};
// labels to indicate padding
// No padding
create_label(
&mut commands,
(-250.0, 330.0, 0.0),
"No padding",
text_style.clone(),
);
// Padding
create_label(&mut commands, (250.0, 330.0, 0.0), "Padding", text_style);
// get handle to a sprite to render
let vendor_handle: Handle<Image> = asset_server
.get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png")
.unwrap();
// get index of the sprite in the texture atlas, this is used to render the sprite
// the index is the same for all the texture atlases, since they are created from the same folder
let vendor_index = texture_atlas_linear
.get_texture_index(&vendor_handle)
.unwrap();
// configuration array to render sprites through iteration
let configurations: [(&str, Handle<TextureAtlasLayout>, Handle<Image>, f32); 4] = [
("Linear", atlas_linear_handle, linear_texture, -350.0),
("Nearest", atlas_nearest_handle, nearest_texture, -150.0),
(
"Linear",
atlas_linear_padded_handle,
linear_padded_texture,
150.0,
),
(
"Nearest",
atlas_nearest_padded_handle,
nearest_padded_texture,
350.0,
),
];
// label text style
let sampling_label_style = TextStyle {
font,
font_size: 30.0,
..default()
};
let base_y = 170.0; // y position of the sprites
for (sampling, atlas_handle, image_handle, x) in configurations {
// render a sprite from the texture_atlas
create_sprite_from_atlas(
&mut commands,
(x, base_y, 0.0),
vendor_index,
atlas_handle,
image_handle,
);
// render a label to indicate the sampling setting
create_label(
&mut commands,
(x, base_y + 110.0, 0.0), // offset to y position of the sprite
sampling,
sampling_label_style.clone(),
);
}
}
sourcepub fn get_id_handle<A>(&self, id: AssetId<A>) -> Option<Handle<A>>where
A: Asset,
pub fn get_id_handle<A>(&self, id: AssetId<A>) -> Option<Handle<A>>where
A: Asset,
Get a Handle
from an AssetId
.
This only returns Some
if id
is derived from a Handle
that was
loaded through an AssetServer
, otherwise it returns None
.
Consider using Assets::get_strong_handle
in the case the Handle
comes from Assets::add
.
sourcepub fn get_id_handle_untyped(&self, id: UntypedAssetId) -> Option<UntypedHandle>
pub fn get_id_handle_untyped(&self, id: UntypedAssetId) -> Option<UntypedHandle>
Get an UntypedHandle
from an UntypedAssetId
.
See AssetServer::get_id_handle
for details.
sourcepub fn is_managed(&self, id: impl Into<UntypedAssetId>) -> bool
pub fn is_managed(&self, id: impl Into<UntypedAssetId>) -> bool
Returns true
if the given id
corresponds to an asset that is managed by this AssetServer
.
Otherwise, returns false
.
sourcepub fn get_path_id<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<UntypedAssetId>
pub fn get_path_id<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<UntypedAssetId>
Returns an active untyped asset id for the given path, if the asset at the given path has already started loading, or is still “alive”. Returns the first ID in the event of multiple assets being registered against a single path.
§See also
get_path_ids
for all handles.
sourcepub fn get_path_ids<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Vec<UntypedAssetId>
pub fn get_path_ids<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Vec<UntypedAssetId>
Returns all active untyped asset IDs for the given path, if the assets at the given path have already started loading,
or are still “alive”.
Multiple IDs will be returned in the event that a single path is used by multiple AssetLoader
’s.
sourcepub fn get_handle_untyped<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<UntypedHandle>
pub fn get_handle_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<UntypedHandle>
Returns an active untyped handle for the given path, if the asset at the given path has already started loading, or is still “alive”. Returns the first handle in the event of multiple assets being registered against a single path.
§See also
get_handles_untyped
for all handles.
sourcepub fn get_handles_untyped<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Vec<UntypedHandle>
pub fn get_handles_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Vec<UntypedHandle>
Returns all active untyped handles for the given path, if the assets at the given path have already started loading,
or are still “alive”.
Multiple handles will be returned in the event that a single path is used by multiple AssetLoader
’s.
sourcepub fn get_path_and_type_id_handle(
&self,
path: &AssetPath<'_>,
type_id: TypeId,
) -> Option<UntypedHandle>
pub fn get_path_and_type_id_handle( &self, path: &AssetPath<'_>, type_id: TypeId, ) -> Option<UntypedHandle>
Returns an active untyped handle for the given path and TypeId
, if the asset at the given path has already started loading,
or is still “alive”.
sourcepub fn get_path(&self, id: impl Into<UntypedAssetId>) -> Option<AssetPath<'_>>
pub fn get_path(&self, id: impl Into<UntypedAssetId>) -> Option<AssetPath<'_>>
Returns the path for the given id
, if it has one.
sourcepub fn mode(&self) -> AssetServerMode
pub fn mode(&self) -> AssetServerMode
Returns the AssetServerMode
this server is currently in.
sourcepub fn preregister_loader<L>(&self, extensions: &[&str])where
L: AssetLoader,
pub fn preregister_loader<L>(&self, extensions: &[&str])where
L: AssetLoader,
Pre-register a loader that will later be added.
Assets loaded with matching extensions will be blocked until the real loader is added.
Trait Implementations§
source§impl Clone for AssetServer
impl Clone for AssetServer
source§fn clone(&self) -> AssetServer
fn clone(&self) -> AssetServer
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl Debug for AssetServer
impl Debug for AssetServer
impl Resource for AssetServer
Auto Trait Implementations§
impl Freeze for AssetServer
impl !RefUnwindSafe for AssetServer
impl Send for AssetServer
impl Sync for AssetServer
impl Unpin for AssetServer
impl !UnwindSafe for AssetServer
Blanket Implementations§
source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§default unsafe fn clone_to_uninit(&self, dst: *mut T)
default unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more