Skip to content
Snippets Groups Projects
Verified Commit 4ba78a2b authored by Louis's avatar Louis :fire:
Browse files

Import from cresthollow

parents
Branches trunk
No related tags found
No related merge requests found
/target
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Environment-dependent path to Maven home directory
/mavenHomeManager.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/weirdboi_build_step.iml" filepath="$PROJECT_DIR$/.idea/weirdboi_build_step.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
This diff is collapsed.
[package]
name = "weirdboi_build_step"
version = "0.1.0"
edition = "2024"
[dependencies]
crunch-cli = { git = "https://weirdboi.dev/microhacks/crunch.git", rev = "02fb9b48f29b38d3b9b8b280c1bab8c1b6cd51f3" }
bevy_math = "0.16"
bevy_image = { version = "0.16" , features = ["serialize"] }
micro_banimate = "0.11"
image = "0.25"
etagere = "0.2"
heck = "0.5"
oxipng = "9.1.5"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
num-traits = "0.2.19"
walkdir = "2.5"
LICENSE 0 → 100644
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Louis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# Asset Build Tools
Utilities to include in your `build.rs` to optimise game assets
## Utilities
- `optimise_images(input_folder, output_folder)` - Recursively copy all .png images from the input folder into the output folder, applying heavy file size optimisations such as stripping any data not directly related to reading the image bytes. The folder structure in input_folder is maintained in output_folder.
- `optimise_atlas(input_folder, output_folder, tile_size)` - Perform the same optimisations as `optimise_images`, but also interpret each image as a texture atlas and extrude each tile by a fixed amount. A serialised `TextureAtlasLayout` is also saved alongside the image in the output_folder
- `build_animations(input_folder, output_folder)` - Recursively search the input folder for animation spec files, and produce an optimised texture atlas image, texture atlas layout, and micro_banimate compatible aniamtion config in the output folder.
### `build_animations`
This utility will search for any files with the `.animdata.json` extension, which expects the following format:
```rust
pub struct AnimationData {
/// The path relative to the animdata file that contains zero or more sprite sheet fragments, to
/// be built in to the animated atlas
asset_path: String,
/// The dimensions of each frame within a sprite sheet, used to calculate atlas coordinates and inferring row layouts
frame_size: FrameSize,
/// The duration in seconds of each frame in the animation, unless specified otherwise
frame_secs: f32,
/// A map of animation names to their respective frame durations in seconds. Entry names are non-suffixed,
/// relating to the name of the animation without directional information (e.g. "idle" rather than "idle_right_down")
frame_override: HashMap<String, f32>,
/// A list of animation names that should be marked as a loop
should_loop: HashSet<String>,
}
```
- `asset_path` should point to a folder. The folder should contain images, each of which will be treated as a named animation
- `frame_size` should either be a single integer pixel size for square frames (e.g. `frame_size: 16`), or a two integer tuple representing width and height for rectangular frames (e.g. `frame_size: [8, 16]`)
- `frame_override`, `should_loop`: The name of the file is the name that will be used in the generated atlas, and so the values provided for looping and overrides should exactly match the file name _without the extension_
\ No newline at end of file
hard_tabs = true
use_field_init_shorthand = true
use_try_shorthand = true
\ No newline at end of file
use crate::data::{AnimationData, AnimationType, FrameSize, GeneratedAtlasSpec};
use crate::utils::file_name;
use etagere::Rectangle;
use heck::ToSnakeCase;
use micro_banimate::definitions::{AnimationFrames, AnimationSet};
use std::collections::HashMap;
use std::path::PathBuf;
pub fn build_animation_library<'a>(
atlas_data: &'a AnimationData,
atlas_def: &'a GeneratedAtlasSpec<'a>,
) -> AnimationSet {
let frame_size = atlas_data.frame_size;
let atlas_width = atlas_def.width / frame_size.width() as i32;
let mut output = HashMap::with_capacity(atlas_def.allocations.len());
for (path, region) in &atlas_def.allocations {
let animation_name = match file_name(path) {
Some(name) => name,
None => {
eprintln!(
"[Anim] Couldn't create name for animation at path: {:?}",
path
);
continue;
}
};
let frame_time = atlas_data
.frame_override
.get(animation_name.as_str())
.copied()
.unwrap_or(atlas_data.frame_secs);
let _should_loop = atlas_data.should_loop.contains(animation_name.as_str());
match infer_animation_type(frame_size, region) {
AnimationType::Single => {
let names = [format!("{}_right_down", &animation_name), animation_name];
let frames = frame_count(frame_size, region);
let (h_frame, v_frame) = first_frame(frame_size, region);
let index = initial_index(h_frame, v_frame, atlas_width);
let frame_list: Vec<usize> = (0..frames).map(|i| index + i as usize).collect();
for name in names {
output.insert(
name,
AnimationFrames {
frames: frame_list.clone(),
frame_secs: frame_time,
// loops: should_loop,
},
);
}
}
AnimationType::Directional => {
let names = ["right_down", "left_down", "right_up", "left_up"];
for (v_diff, name) in names.iter().enumerate() {
let frames = frame_count(frame_size, region);
let (h_frame, v_frame) = first_frame(frame_size, region);
let index = initial_index(h_frame, v_frame + v_diff as i32, atlas_width);
let frame_list: Vec<usize> = (0..frames).map(|i| index + i as usize).collect();
output.insert(
format!("{}_{}", &animation_name, name),
AnimationFrames {
frames: frame_list.clone(),
frame_secs: frame_time,
// loops: should_loop,
},
);
}
}
AnimationType::Unsupported => {
eprintln!(
"[Anim] Skipping unsupported animation layout for {:?}",
path
);
}
}
}
AnimationSet(output)
}
/// Convert the xy coordinate of a sprite in the atlas into a 1d index into an array
fn initial_index(x: i32, y: i32, width: i32) -> usize {
x as usize + y as usize * width as usize
}
#[inline(always)]
fn infer_animation_type(frame_size: FrameSize, region: &Rectangle) -> AnimationType {
let region_height = region.height() as u32;
if frame_size.height() == region_height {
AnimationType::Single
} else if frame_size.height() * 4 == region_height {
AnimationType::Directional
} else {
AnimationType::Unsupported
}
}
#[inline(always)]
fn frame_count(frame_size: FrameSize, region: &Rectangle) -> u32 {
region.width() as u32 / frame_size.width()
}
#[inline(always)]
fn first_frame(frame_size: FrameSize, region: &Rectangle) -> (i32, i32) {
let frame_width = frame_size.width() as i32;
let frame_height = frame_size.height() as i32;
let top_left = region.min; // Pixel coordinates
(top_left.x / frame_width, top_left.y / frame_height) // Convert to frame space
}
use image::ImageError;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fs;
use std::path::{PathBuf, StripPrefixError};
/// A representation of a number of different configurations for creating a packed texture atlas
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Default)]
pub enum AtlasPackingStyle {
/// Create a packed texture atlas that uses a fixed width (typically the widest individual input texture)
/// and a variable height, with the maximum height being the total combined height of every input for a
/// pathological case
#[default]
ExtendVertical,
}
/// Texture atlas metadata for a whole packed texture atlas
#[derive(Debug)]
pub struct GeneratedAtlasSpec<'atlas> {
/// Total horizontal pixel size of the output texture
pub width: i32,
/// Total vertical pixel size of the output texture
pub height: i32,
/// A file path to atlas region mapping of every input texture that should be packed into the atlas
pub allocations: AtlasMap<'atlas>,
}
/// A mapping of image paths to their corresponding atlas allocations
pub type AtlasMap<'atlas> = HashMap<&'atlas PathBuf, etagere::Rectangle>;
/// Builder type for creating packed textures out of a series of file paths pointing to images. Will
/// inspect images to create a best-effort layout, with no guarantee that a more optimal layout could
/// not be created manually
pub struct AtlasBatch<'atlas> {
/// A list of input files representing images. Paths are not checked on construction, so if any of the
/// paths do not represent valid images, the builder methods will return an error when called.
pub paths: &'atlas [PathBuf],
/// Currently unused; assumed to be [AtlasPackingStyle::ExtendVertical].
/// How the atlas should be laid out when generating the atlas spec
pub packing_style: AtlasPackingStyle,
}
impl<'atlas> AtlasBatch<'atlas> {
/// Create a new builder that will generate an atlas for files at the provided paths, using the
/// default packing strategy
pub fn new(paths: &'atlas [PathBuf]) -> Self {
AtlasBatch {
paths,
packing_style: Default::default(),
}
}
}
#[derive(Copy, Clone, Deserialize)]
#[serde(untagged)]
pub enum FrameSize {
Rectangle((u32, u32)),
Square(u32),
}
impl FrameSize {
pub fn width(&self) -> u32 {
match self {
FrameSize::Rectangle((width, _)) => *width,
FrameSize::Square(size) => *size,
}
}
pub fn height(&self) -> u32 {
match self {
FrameSize::Rectangle((_, height)) => *height,
FrameSize::Square(size) => *size,
}
}
}
#[derive(Clone, Deserialize)]
pub struct AnimationData {
/// The path relative to the animdata file that contains zero or more sprite sheet fragments, to
/// be built in to the animated atlas
pub asset_path: String,
/// The dimensions of each frame within a sprite sheet, used to calculate atlas coordinates and inferring row layouts
pub frame_size: FrameSize,
/// The duration in seconds of each frame in the animation, unless specified otherwise
pub frame_secs: f32,
/// A map of animation names to their respective frame durations in seconds. Entry names are non-suffixed,
/// relating to the name of the animation without directional information (e.g. "idle" rather than "idle_right_down")
#[serde(default)]
pub frame_override: HashMap<String, f32>,
/// A list of animation names that should be marked as a loop
#[serde(default)]
pub should_loop: HashSet<String>,
}
impl TryFrom<PathBuf> for AnimationData {
type Error = std::io::Error;
fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
let content = fs::read_to_string(path)?;
serde_json::from_str(&content).map_err(|e| e.into())
}
}
pub enum AnimationType {
Single,
Directional,
Unsupported,
}
#[derive(Debug)]
pub enum BuildError {
InvalidFilePath(String),
ImageError(ImageError),
AtlasError(String),
IoError(std::io::Error),
SerdeError(serde_json::Error),
}
impl BuildError {
pub fn atlas_error(&self, err: impl ToString) -> Self {
BuildError::AtlasError(err.to_string())
}
}
impl From<ImageError> for BuildError {
fn from(value: ImageError) -> Self {
BuildError::ImageError(value)
}
}
impl From<std::io::Error> for BuildError {
fn from(value: std::io::Error) -> Self {
BuildError::IoError(value)
}
}
impl From<serde_json::Error> for BuildError {
fn from(value: serde_json::Error) -> Self {
BuildError::SerdeError(value)
}
}
impl From<StripPrefixError> for BuildError {
fn from(value: StripPrefixError) -> Self {
Self::InvalidFilePath(value.to_string())
}
}
impl Display for BuildError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
BuildError::InvalidFilePath(path) => write!(f, "Invalid file path: {}", path),
BuildError::ImageError(err) => write!(f, "{}", err),
BuildError::AtlasError(err) => write!(f, "{}", err),
BuildError::IoError(err) => write!(f, "I/O error: {}", err),
BuildError::SerdeError(err) => write!(f, "Format error: {}", err),
}
}
}
impl Error for BuildError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
BuildError::ImageError(ie) => Some(ie),
BuildError::IoError(er) => Some(er),
BuildError::SerdeError(serr) => Some(serr),
_ => None,
}
}
}
use crate::FrameSize;
use crate::animation_set::build_animation_library;
use crate::data::{AnimationData, AtlasBatch, AtlasPackingStyle, BuildError, GeneratedAtlasSpec};
use crate::utils::{
ensure_dir, file_name, find_files_with_extension, image_dimensions, load_image,
write_animation_set, write_image, write_json,
};
use bevy_image::TextureAtlasLayout;
use bevy_math::UVec2;
use crunch_cli::actions::ExtrudeOptions;
use etagere::{AtlasAllocator, point2, size2};
use image::{DynamicImage, GenericImage, GenericImageView};
use num_traits::AsPrimitive;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
const ATLAS_SPACING: u32 = 2;
const ATLAS_PADDING: u32 = 1;
pub struct ExtrusionOutput {
pub layout: TextureAtlasLayout,
pub atlas: DynamicImage,
}
pub fn build_animations(
input_directory: impl AsRef<Path>,
output_directory: impl AsRef<Path>,
) -> Result<(), BuildError> {
ensure_dir(&input_directory);
ensure_dir(&output_directory);
let animation_data_files = find_files_with_extension(input_directory, "animdata.json");
for data_file in animation_data_files {
build_animation(data_file, output_directory.as_ref())?;
}
Ok(())
}
pub fn build_animation(data_path: PathBuf, output_directory: &Path) -> Result<(), BuildError> {
let directory = data_path
.parent()
.expect("Invalid animation data path")
.to_path_buf();
let entity_name = file_name(&data_path)
.ok_or_else(|| BuildError::InvalidFilePath(String::from("Invalid animation data file")))?;
let (entity_name, _) = entity_name.split_at(entity_name.len() - 9);
let data = AnimationData::try_from(data_path).expect("Invalid animation data file");
let sprite_directory = directory.join(&data.asset_path);
if !sprite_directory.exists() {
panic!("Sprite directory does not exist: {:?}", sprite_directory);
}
let images = find_files_with_extension(sprite_directory, ".png");
let batch = AtlasBatch::new(&images);
let spec = batch.allocate_space()?;
let output_image = batch.build()?;
let animation_data = build_animation_library(&data, &spec);
let (t_wid, t_hei, columns, rows) = match data.frame_size {
FrameSize::Square(len) => (len, len, spec.width as u32 / len, spec.height as u32 / len),
FrameSize::Rectangle((width, height)) => (
width,
height,
spec.width as u32 / width,
spec.height as u32 / height,
),
};
let image_output_path = output_directory.join(format!("{}.png", entity_name));
let animation_output_path = output_directory.join(format!("{}.anim.json", entity_name));
let atlas_output_path = output_directory.join(format!("{}.atlas.json", entity_name));
write_image(image_output_path, &output_image)?;
write_animation_set(animation_output_path, &animation_data)?;
write_json(
atlas_output_path,
&TextureAtlasLayout::from_grid(UVec2::new(t_wid, t_hei), columns, rows, None, None),
)?;
Ok(())
}
impl<'atlas> AtlasBatch<'atlas> {
/// Directly build an atlas from the given paths without emitting intermediate artifacts
///
/// ## Example
///
/// ```rust,no_run
/// use weirdboi_build::{AtlasBatch, BuildError};
/// use std::path::PathBuf;
///
/// fn main() -> Result<(), BuildError> {
/// let atlas_texture = AtlasBatch::new(&[
/// PathBuf::from("relative/path/to/image1.png"),
/// PathBuf::from("relative/path/to/image2.png"),
/// ]).build()?;
/// # Ok(())
/// }
/// ```
pub fn build(&self) -> Result<DynamicImage, BuildError> {
AtlasBatch::generate_atlas(&self.allocate_space()?)
}
/// Generate a settings object that can be used to configure other types or provide image metadata
/// without having to re-process a generated atlas texture
///
/// This method will access the filesystem, but will only read file metadata (e.g. dimensions), and
/// will not load whole images into memory
pub fn allocate_space(&self) -> Result<GeneratedAtlasSpec<'atlas>, BuildError> {
let mut max_width = 0;
let mut max_height = 0;
let mut size_cache = Vec::with_capacity(self.paths.len());
let mut allocations = HashMap::new();
for path in self.paths {
let (width, height) = image_dimensions(path)?;
match self.packing_style {
AtlasPackingStyle::ExtendVertical => {
max_width = max_width.max(width);
max_height += height;
}
}
size_cache.push((path, size2(width.as_(), height.as_())));
}
let mut alloc = AtlasAllocator::new(size2(max_width.as_(), max_height.as_()));
for (path, size) in size_cache {
let allocation = match alloc.allocate(size) {
Some(allocation) => allocation,
None => {
return Err(BuildError::AtlasError(format!(
"Unable to allocate for {:?}",
path
)));
}
};
allocations.insert(path, allocation.rectangle);
}
// The box packing algo intentionally allocates too much vertical space, assuming that we
// have a pathological case that stacks every sprite vertically. In most cases, there will
// be excess blank space at the bottom of the atlas, so we virtually crop that by calculating
// the _real_ used space, by assuming a [0,0] top left coordinate and finding the largest
// 2D extents
let mut maximal_point = point2(0, 0);
for allocated in allocations.values() {
maximal_point = maximal_point.max(allocated.max);
}
Ok(GeneratedAtlasSpec {
allocations,
width: maximal_point.x,
height: maximal_point.y,
})
}
/// Generate a packed atlas texture from a previously calculated set of allocations
///
/// This method will access the filesystem, and will load whole images into memory sequentially.
/// The total amount of memory required is equal to the requirements of an RGBA8 format image with the dimensions from
/// the atlas spec, and the requirements of the current image being packed. Single images are deallocated after being packed.
pub fn generate_atlas(atlas_spec: &GeneratedAtlasSpec) -> Result<DynamicImage, BuildError> {
let mut atlas_image =
image::ImageBuffer::new(atlas_spec.width.as_(), atlas_spec.height.as_());
for (path, allocation) in atlas_spec.allocations.iter() {
let image = load_image(path)?;
atlas_image
.copy_from(&image, allocation.min.x.as_(), allocation.min.y.as_())
.map_err(BuildError::ImageError)?;
}
Ok(DynamicImage::from(atlas_image))
}
}
pub fn extrude_atlas(
tile_size: u32,
atlas_image: &DynamicImage,
) -> Result<ExtrusionOutput, BuildError> {
let extrusion = ExtrudeOptions {
tile_size,
space_x: ATLAS_SPACING,
space_y: ATLAS_SPACING,
padding: ATLAS_PADDING,
extrude: true,
};
let (width, height) = atlas_image.dimensions();
let atlas_layout = TextureAtlasLayout::from_grid(
UVec2::splat(tile_size),
width / tile_size,
height / tile_size,
Some(UVec2::splat(ATLAS_SPACING)),
Some(UVec2::splat(ATLAS_PADDING)),
);
let extruded_atlas = extrusion
.extrude(atlas_image)
.map_err(|e| BuildError::AtlasError(format!("{e}")))?;
Ok(ExtrusionOutput {
layout: atlas_layout,
atlas: extruded_atlas.into(),
})
}
This diff is collapsed.
mod animation_set;
mod data;
mod image_atlas;
mod images;
mod utils;
pub use data::{AnimationData, AtlasBatch, BuildError, FrameSize};
pub use image_atlas::build_animations;
pub use images::{optimise_atlas, optimise_images};
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment