Skip to content

Change from_grid_with_padding API #1086

Closed
@ryanleecode

Description

@ryanleecode

The current API of from_grid_with_padding seems fairly strange because it forces you to specify the number of rows & columns when that should be computed instead. I propose changing it to take the texture dimensions instead.

I also think the API should add padding to 0th column because texture clamping can cause it to bleed without.

New Proposed API

pub fn from_grid_with_padding(
    texture: Handle<Texture>,
    tile_size: Vec2,
    texture_dimensions: Vec2,
    padding: Vec2,
) -> TextureAtlas {
    let mut sprites = Vec::new();
    let rows = (texture_dimensions.x() / (tile_size.x() + (padding.x() * 2.0))) as i32;
    let columns = (texture_dimensions.y() / (tile_size.y() + (padding.y() * 2.0))) as i32;

    for y in 0..rows {
        for x in 0..columns {
            let rect_min = Vec2::new(
                (tile_size.x() + (padding.x() * 2.0)) * x as f32 + padding.x(),
                (tile_size.y() + (padding.y() * 2.0)) * y as f32 + padding.y(),
            );

            sprites.push(Rect {
                min: rect_min,
                max: Vec2::new(rect_min.x() + tile_size.x(), rect_min.y() + tile_size.y()),
            })
        }
    }

    TextureAtlas {
        size: texture_dimensions,
        textures: sprites,
        texture,
        texture_handles: None,
    }
}

Old API:

pub fn from_grid_with_padding(
    texture: Handle<Texture>,
    tile_size: Vec2,
    columns: usize,
    rows: usize,
    padding: Vec2,
) -> TextureAtlas {
    let mut sprites = Vec::new();
    let mut x_padding = 0.0;
    let mut y_padding = 0.0;

    for y in 0..rows {
        if y > 0 {
            y_padding = padding.y();
        }
        for x in 0..columns {
            if x > 0 {
                x_padding = padding.x();
            }

            let rect_min = Vec2::new(
                (tile_size.x() + x_padding) * x as f32,
                (tile_size.y() + y_padding) * y as f32,
            );

            sprites.push(Rect {
                min: rect_min,
                max: Vec2::new(rect_min.x() + tile_size.x(), rect_min.y() + tile_size.y()),
            })
        }
    }

    TextureAtlas {
        size: Vec2::new(
            ((tile_size.x() + x_padding) * columns as f32) - x_padding,
            ((tile_size.y() + y_padding) * rows as f32) - y_padding,
        ),
        textures: sprites,
        texture,
        texture_handles: None,
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-RenderingDrawing game state to the screenC-Code-QualityA section of code that is hard to understand or changeC-UsabilityA targeted quality-of-life change that makes Bevy easier to use

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions