Skip to content

Commit

Permalink
texture atlas layout in the texture atlas module
Browse files Browse the repository at this point in the history
  • Loading branch information
ManevilleF committed Mar 25, 2023
1 parent 8ec1e90 commit 4560929
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 139 deletions.
5 changes: 1 addition & 4 deletions crates/bevy_sprite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ mod render;
mod sprite;
mod texture_atlas;
mod texture_atlas_builder;
mod texture_atlas_layout;

pub mod collide_aabb;

Expand All @@ -14,8 +13,7 @@ pub mod prelude {
pub use crate::{
bundle::{SpriteBundle, SpriteSheetBundle},
sprite::Sprite,
texture_atlas::TextureAtlas,
texture_atlas_layout::TextureAtlasLayout,
texture_atlas::{TextureAtlas, TextureAtlasLayout},
ColorMaterial, ColorMesh2dBundle, TextureAtlasBuilder,
};
}
Expand All @@ -27,7 +25,6 @@ pub use render::*;
pub use sprite::*;
pub use texture_atlas::*;
pub use texture_atlas_builder::*;
pub use texture_atlas_layout::*;

use bevy_app::prelude::*;
use bevy_asset::{AddAsset, Assets, HandleUntyped};
Expand Down
137 changes: 130 additions & 7 deletions crates/bevy_sprite/src/texture_atlas.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
use crate::TextureAtlasLayout;
use bevy_asset::{Assets, Handle};
use bevy_ecs::component::Component;
use bevy_math::Rect;
use bevy_reflect::Reflect;
use bevy_math::{Rect, Vec2};
use bevy_reflect::{FromReflect, Reflect, TypeUuid};
use bevy_render::texture::Image;
use bevy_utils::HashMap;

/// Maps a layout for a texture. Used with the [`TextureAtlas`] component it allows to
/// either draw a specific area of the target texture, or to animate a sprite sheet.
///
/// Optionaly it can store a mapping from sub texture handles to the related area index (see
/// [`TextureAtlasBuilder`]).
///
/// [Example usage animating sprite.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_sheet.rs)
/// [Example usage loading sprite sheet.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/texture_atlas.rs)
///
/// [`TextureAtlasBuilder`]: crate::TextureAtlasBuilder
#[derive(Reflect, FromReflect, Debug, Clone, TypeUuid)]
#[uuid = "7233c597-ccfa-411f-bd59-9af349432ada"]
#[reflect(Debug)]
pub struct TextureAtlasLayout {
// TODO: add support to Uniforms derive to write dimensions and sprites to the same buffer
pub size: Vec2,
/// The specific areas of the atlas where each texture can be found
pub textures: Vec<Rect>,
/// Texture handle to area index mapping. Set by [`TextureAtlasBuilder`].
///
/// [`TextureAtlasBuilder`]: crate::TextureAtlasBuilder
pub texture_handles: Option<HashMap<Handle<Image>, usize>>,
}

/// Component used to draw a specific section of a texture.
///
Expand All @@ -23,13 +48,102 @@ pub struct TextureAtlas {
pub index: usize,
}

impl From<Handle<TextureAtlasLayout>> for TextureAtlas {
fn from(texture_atlas: Handle<TextureAtlasLayout>) -> Self {
impl TextureAtlasLayout {
/// Create a new empty layout with custom `dimensions`
pub fn new_empty(dimensions: Vec2) -> Self {
Self {
layout: texture_atlas,
index: 0,
size: dimensions,
texture_handles: None,
textures: Vec::new(),
}
}

/// Generate a [`TextureAtlasLayout`] as a grid where each
/// `tile_size` by `tile_size` grid-cell is one of the *section* in the
/// atlas. Grid cells are separated by some `padding`, and the grid starts
/// at `offset` pixels from the top left corner. Resulting layout is
/// indexed left to right, top to bottom.
///
/// # Arguments
///
/// * `tile_size` - Each layout grid cell size
/// * `columns` - Grid column count
/// * `rows` - Grid row count
/// * `padding` - Optional padding between cells
/// * `offset` - Optional global grid offset
pub fn from_grid(
tile_size: Vec2,
columns: usize,
rows: usize,
padding: Option<Vec2>,
offset: Option<Vec2>,
) -> Self {
let padding = padding.unwrap_or_default();
let offset = offset.unwrap_or_default();
let mut sprites = Vec::new();
let mut current_padding = Vec2::ZERO;

for y in 0..rows {
if y > 0 {
current_padding.y = padding.y;
}
for x in 0..columns {
if x > 0 {
current_padding.x = padding.x;
}

let cell = Vec2::new(x as f32, y as f32);

let rect_min = (tile_size + current_padding) * cell + offset;

sprites.push(Rect {
min: rect_min,
max: rect_min + tile_size,
});
}
}

let grid_size = Vec2::new(columns as f32, rows as f32);

Self {
size: ((tile_size + current_padding) * grid_size) - current_padding,
textures: sprites,
texture_handles: None,
}
}

/// Add a *section* to the list in the layout and returns its index
/// which can be used with [`TextureAtlas`]
///
/// # Arguments
///
/// * `rect` - The section of the texture to be added
///
/// [`TextureAtlas`]: crate::TextureAtlas
pub fn add_texture(&mut self, rect: Rect) -> usize {
self.textures.push(rect);
self.textures.len() - 1
}

/// How many textures are in the `TextureAtlas`
pub fn len(&self) -> usize {
self.textures.len()
}

pub fn is_empty(&self) -> bool {
self.textures.is_empty()
}

/// Retrieves the texture *section* index of the given `texture` handle.
///
/// This requires the layout to have been built using a [`TextureAtlasBuilder`]
///
/// [`TextureAtlasBuilder`]: crate::TextureAtlasBuilder
pub fn get_texture_index(&self, texture: &Handle<Image>) -> Option<usize> {
self.texture_handles
.as_ref()
.and_then(|texture_handles| texture_handles.get(texture).cloned())
}
}

impl TextureAtlas {
Expand All @@ -39,3 +153,12 @@ impl TextureAtlas {
atlas.textures.get(self.index).copied()
}
}

impl From<Handle<TextureAtlasLayout>> for TextureAtlas {
fn from(texture_atlas: Handle<TextureAtlasLayout>) -> Self {
Self {
layout: texture_atlas,
index: 0,
}
}
}
128 changes: 0 additions & 128 deletions crates/bevy_sprite/src/texture_atlas_layout.rs

This file was deleted.

0 comments on commit 4560929

Please sign in to comment.