GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
SpriteAtlas.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_GRAPHICS_SPRITE_ATLAS_HPP
5#define GREM_GRAPHICS_SPRITE_ATLAS_HPP
6
8
13#include <GREM/core/extents.hpp>
15#include <GREM/core/math.hpp>
20
21#include <cstddef> // std::size_t
22#include <functional> // std::hash
23#include <stdexcept> // std::length_error
24#include <utility> // std::move
25
26namespace grem::graphics {
27
28class Device; // Forward declaration, to avoid including Device.hpp.
29class SpriteAtlas; // Forward declaration.
30
38 using Flip = uint8_t;
39
43 enum FlipAxis : Flip { // NOLINT(cppcoreguidelines-use-enum-class)
44 NO_FLIP = 0,
46 FLIP_VERTICALLY = 1 << 1,
47 };
48
53
60
68 [[nodiscard]] bool operator==(const SpriteOptions& other) const = default;
69};
70
79
85 uint32_t initialResolution = 128;
86
90 uint32_t padding = 0;
91
106 uint32_t alignment = 16;
107
112 .minificationFilter = TextureFilter::NEAREST,
113 .magnificationFilter = TextureFilter::NEAREST,
114 .mipmapMode = TextureMipmapMode::NEAREST,
115 .horizontalWrappingMode = TextureWrappingMode::CLAMP_TO_EDGE,
116 .verticalWrappingMode = TextureWrappingMode::CLAMP_TO_EDGE,
117 .maxAnisotropy = 1.0f,
118 };
119};
120
124struct SpriteID {
125public:
129 constexpr SpriteID() noexcept = default;
130
137 constexpr explicit operator bool() const noexcept {
138 return *this != SpriteID{};
139 }
140
148 [[nodiscard]] constexpr bool operator==(const SpriteID& other) const noexcept = default;
149
157 [[nodiscard]] constexpr std::strong_ordering operator<=>(const SpriteID& other) const noexcept = default;
158
159private:
160 friend SpriteAtlas;
161 friend std::hash<SpriteID>;
162
163 constexpr explicit SpriteID(uint32_t index) noexcept
164 : index(index) {}
165
166 uint32_t index = Limits<uint32_t>::MAX;
167};
168
174public:
183
191 explicit SpriteAtlas(Device& device, const SpriteAtlasOptions& options = {})
192 : device(&device)
193 , atlasPacker({.initialResolution = options.initialResolution, .padding = options.padding, .alignment = options.alignment})
194 , options(options) {}
195
199 void clear() noexcept {
200 sprites.clear();
201 atlasPacker = resource::AtlasPacker{{.initialResolution = atlasPacker.getResolution(), .padding = options.padding, .alignment = options.alignment}};
202 }
203
224 [[nodiscard]] SpriteID insertSprite(const resource::ImageView& image, const SpriteOptions& spriteOptions = {}) {
226 throw graphics::Error{"Failed to insert sprite image: Incompatible image format."};
227 }
228
229 if (sprites.size() >= size_t{Limits<uint32_t>::MAX}) {
230 throw std::length_error{"Maximum sprite count exceeded."};
231 }
232
233 const auto [offset, resized] = atlasPacker.insertRectangle(image.getSize2D());
234 if (!atlasTexture || resized) {
235 Texture oldAtlasTexture = std::move(atlasTexture);
236 const Extent2D size{static_cast<uint32_t>(atlasPacker.getResolution())};
237 uint32_t mipLevelCount = 1;
238 if (options.samplerOptions.mipmapMode != TextureMipmapMode::NONE) {
240 }
241 atlasTexture = Texture::create(*device, TextureType::TEXTURE_2D, options.internalFormat, size, mipLevelCount, ClearValues{}, options.samplerOptions);
242 if (oldAtlasTexture) {
243 atlasTexture.pasteTexture(oldAtlasTexture);
244 }
245 }
246
247 resource::Image transformedImage{};
248 resource::ImageView transformedImageView = image;
249 if (spriteOptions.convertToPremultipliedAlpha && resource::Image::isRGBAColorFormat(transformedImageView.getFormat()) &&
250 resource::Image::isRawFormat(transformedImageView.getFormat())) {
251 transformedImage = resource::Image{transformedImageView};
252 transformedImage.transformFromStraightToPremultipliedAlpha(Texture::getTransferFunction(options.internalFormat));
253 transformedImageView = transformedImage;
254 }
255 if (options.padding > 0) {
256 transformedImage = transformedImageView.getPadded(options.padding);
257 transformedImageView = transformedImage;
258 }
259 atlasTexture.pasteImage(Extent2D{transformedImageView.getWidth(), transformedImageView.getHeight()}, transformedImageView.data(),
260 Offset2D{.x = offset.x - static_cast<int32_t>(options.padding), .y = offset.y - static_cast<int32_t>(options.padding)});
261
262 const vec2 position{static_cast<float>(offset.x), static_cast<float>(offset.y)};
263 const vec2 size{static_cast<float>(image.getWidth()), static_cast<float>(image.getHeight())};
264
265 const uint32_t index = static_cast<uint32_t>(sprites.size());
266 sprites.push_back(Sprite{.position = position, .size = size, .flip = spriteOptions.flip});
267 return SpriteID{index};
268 }
269
294 if (sprites.size() >= size_t{Limits<uint32_t>::MAX}) {
295 throw std::length_error{"Maximum sprite count exceeded."};
296 }
297
298 const Sprite& baseSprite = getSprite(baseSpriteID);
299 GREM_ASSERT(static_cast<float>(region.offset.x) <= baseSprite.size.x);
300 GREM_ASSERT(static_cast<float>(region.offset.y) <= baseSprite.size.y);
301 GREM_ASSERT(static_cast<float>(region.size.width) <= baseSprite.size.x - static_cast<float>(region.offset.x));
302 GREM_ASSERT(static_cast<float>(region.size.height) <= baseSprite.size.y - static_cast<float>(region.offset.y));
303
304 const vec2 position = baseSprite.position + vec2{static_cast<float>(region.offset.x), static_cast<float>(region.offset.y)};
305 const vec2 size{static_cast<float>(region.size.width), static_cast<float>(region.size.height)};
306
307 const uint32_t index = static_cast<uint32_t>(sprites.size());
308 sprites.push_back(Sprite{.position = position, .size = size, .flip = flip});
309 return SpriteID{index};
310 }
311
324 [[nodiscard]] const Sprite& getSprite(SpriteID id) const {
325 GREM_ASSERT(id.index < sprites.size());
326 return sprites[id.index];
327 }
328
343 [[nodiscard]] Pair<vec2> getSpriteTextureOffsetAndScale(SpriteID id) const noexcept {
344 const Sprite& sprite = getSprite(id);
345 vec2 unnormalizedTextureOffset{};
346 vec2 unnormalizedTextureScale{};
347 if ((sprite.flip & SpriteOptions::FLIP_HORIZONTALLY) != 0) {
348 unnormalizedTextureOffset.x = sprite.position.x + sprite.size.x;
349 unnormalizedTextureScale.x = -sprite.size.x;
350 } else {
351 unnormalizedTextureOffset.x = sprite.position.x;
352 unnormalizedTextureScale.x = sprite.size.x;
353 }
354 if ((sprite.flip & SpriteOptions::FLIP_VERTICALLY) != 0) {
355 unnormalizedTextureOffset.y = sprite.position.y + sprite.size.y;
356 unnormalizedTextureScale.y = -sprite.size.y;
357 } else {
358 unnormalizedTextureOffset.y = sprite.position.y;
359 unnormalizedTextureScale.y = sprite.size.y;
360 }
361 const vec2 textureSize = atlasTexture.getSize2D();
362 const vec2 textureOffset = unnormalizedTextureOffset / textureSize;
363 const vec2 textureScale = unnormalizedTextureScale / textureSize;
364 return {textureOffset, textureScale};
365 }
366
374 [[nodiscard]] const Texture& getAtlasTexture() const noexcept {
375 return atlasTexture;
376 }
377
383 [[nodiscard]] const SpriteAtlasOptions& getOptions() const noexcept {
384 return options;
385 }
386
387private:
388 Device* device;
389 resource::AtlasPacker atlasPacker;
390 Texture atlasTexture{};
391 Buffer<Sprite> sprites{};
392 SpriteAtlasOptions options{};
393};
394
395} // namespace grem::graphics
396
397template <>
398struct std::hash<grem::graphics::SpriteID> {
399 [[nodiscard]] std::size_t operator()(const grem::graphics::SpriteID& spriteID) const {
400 return hasher(spriteID.index);
401 }
402
403private:
404 [[no_unique_address]] std::hash<grem::uint32_t> hasher;
405};
406
407#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Definition Buffer.hpp:28
Persistent system managing the rendering context of a Window.
Definition Device.hpp:68
Expandable texture atlas for packing 2D images into a spritesheet to enable batch rendering.
Definition SpriteAtlas.hpp:173
const Texture & getAtlasTexture() const noexcept
Get a reference to the internal texture atlas.
Definition SpriteAtlas.hpp:374
SpriteAtlas(Device &device, const SpriteAtlasOptions &options={})
Construct an empty sprite atlas.
Definition SpriteAtlas.hpp:191
Pair< vec2 > getSpriteTextureOffsetAndScale(SpriteID id) const noexcept
Get the offset and scale of a specific sprite in the texture atlas.
Definition SpriteAtlas.hpp:343
void clear() noexcept
Clear all inserted sprites and images from the spritesheet.
Definition SpriteAtlas.hpp:199
const SpriteAtlasOptions & getOptions() const noexcept
Get the configuration options of this spritesheet.
Definition SpriteAtlas.hpp:383
SpriteID insertSprite(const resource::ImageView &image, const SpriteOptions &spriteOptions={})
Add a new image to the spritesheet, possibly expanding the texture atlas in order to make space for i...
Definition SpriteAtlas.hpp:224
SpriteID createSubSprite(SpriteID baseSpriteID, Region2D region, SpriteOptions::Flip flip=SpriteOptions::NO_FLIP)
Add a new sprite that is defined as a sub-region of an existing sprite.
Definition SpriteAtlas.hpp:293
const Sprite & getSprite(SpriteID id) const
Get information about a specific image in the spritesheet.
Definition SpriteAtlas.hpp:324
Storage for multidimensional data, such as 2D images, on the GPU, combined with a sampler configurati...
Definition Texture.hpp:700
static constexpr Color::TransferFunction getTransferFunction(TextureFormat internalFormat) noexcept
Get the transfer function of an internal texture format.
Definition Texture.hpp:922
static constexpr bool isCompatibleFormat(TextureFormat internalFormat, resource::ImageFormat format) noexcept
Check if a specific image format is directly compatible with an internal texture format.
Definition Texture.hpp:1158
static Texture create(Device &device, TextureType type, TextureFormat internalFormat, Extent3D size, uint32_t mipLevelCount, const void *pixels, Optional< TextureSamplerOptions > samplerOptions=TextureSamplerOptions{})
Create a new texture object and allocate GPU memory for storing image data.
Axis-aligned rectangle packer for expandable square texture atlases.
Definition AtlasPacker.hpp:53
Read-only non-owning view over a 2D image.
Definition Image.hpp:108
constexpr ImageFormat getFormat() const noexcept
Get the format of the image referenced by this view.
Definition Image.hpp:185
constexpr uint32_t getHeight() const noexcept
Get the height of the image referenced by this view.
Definition Image.hpp:236
constexpr uint32_t getWidth() const noexcept
Get the width of the image referenced by this view.
Definition Image.hpp:227
constexpr Extent2D getSize2D() const noexcept
Get the size, in pixels, of the image layers referenced by this view.
Definition Image.hpp:203
static constexpr bool isRawFormat(ImageFormat format)
Check if a specific image format is a raw format.
Definition Image.hpp:1077
static constexpr bool isRGBAColorFormat(ImageFormat format)
Check if a specific image format is an RGBA color format with an alpha channel.
Definition Image.hpp:1026
static constexpr uint32_t getMaxMipLevelCount(Extent2D size2D) noexcept
Get the maximum number of mip levels for a specific 2D image size.
Definition Image.hpp:960
Definition buffer_layouts.hpp:20
@ CLAMP_TO_EDGE
Clamp to the edge of the texture when sampling outside the 0-1 range.
Definition Texture.hpp:492
TextureFormat
Description of the internal format of a Texture.
Definition Texture.hpp:267
@ R8G8B8A8_SRGB
Raw bitmap where each texel comprises 3 sRGB-encoded and 1 normalized 8-bit unsigned integer componen...
Definition Texture.hpp:277
@ NEAREST
Use the mip level nearest to the displayed size.
Definition Texture.hpp:483
@ NONE
Always use the most detailed mip level (level 0).
Definition Texture.hpp:482
@ NEAREST
Use the nearest neighbor to the sampled texel, which results in a blocky appearance.
Definition Texture.hpp:474
@ TEXTURE_2D
Texture set up to store a single 2D image.
Definition Texture.hpp:39
Definition aliases.hpp:9
vec< 2, float > vec2
Definition math.hpp:438
Extent< 2 > Extent2D
Size of a 2D data region.
Definition extents.hpp:31
Region< 2 > Region2D
Rectangular region of 2D data.
Definition extents.hpp:819
Offset< 2 > Offset2D
Offset in a 2D data region.
Definition extents.hpp:21
GREM_ALWAYS_INLINE constexpr decltype(auto) min(A &&a, B &&b)
Get the smaller of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:585
static constexpr T MAX
Definition fundamentals.hpp:29
Definition Pair.hpp:53
Extent< N > size
Size of the region.
Definition extents.hpp:780
Offset< N > offset
Offset of the region.
Definition extents.hpp:779
Exception type for domain-specific errors originating from the grem::graphics module.
Definition Error.hpp:17
Configuration options for a SpriteAtlas.
Definition SpriteAtlas.hpp:74
TextureSamplerOptions samplerOptions
Sampler options to use for the atlas texture.
Definition SpriteAtlas.hpp:111
uint32_t padding
Empty space to reserve between sprite images, in pixels.
Definition SpriteAtlas.hpp:90
uint32_t alignment
Align padded sprites to a multiple of this number of pixels and limit the number of mip levels in the...
Definition SpriteAtlas.hpp:106
TextureFormat internalFormat
Internal texture format to use for the internal texture atlas.
Definition SpriteAtlas.hpp:78
uint32_t initialResolution
Initial width of the internal texture atlas, in pixels.
Definition SpriteAtlas.hpp:85
Information about a specific image in the spritesheet.
Definition SpriteAtlas.hpp:178
SpriteOptions::Flip flip
Flags that describe how the sprite should be flipped when rendered.
Definition SpriteAtlas.hpp:181
vec2 size
Size of the image in the texture atlas, in texels.
Definition SpriteAtlas.hpp:180
vec2 position
Position of the image in the texture atlas, in texels.
Definition SpriteAtlas.hpp:179
Identifier for a specific image in a SpriteAtlas.
Definition SpriteAtlas.hpp:124
constexpr SpriteID() noexcept=default
Construct an invalid sprite identifier.
constexpr std::strong_ordering operator<=>(const SpriteID &other) const noexcept=default
Compare this identifier to another.
constexpr bool operator==(const SpriteID &other) const noexcept=default
Compare this identifier to another for equality.
Configuration options for a sprite in a SpriteAtlas.
Definition SpriteAtlas.hpp:34
Flip flip
Flags that describe how the sprite should be flipped when rendered.
Definition SpriteAtlas.hpp:52
uint8_t Flip
Flags that describe how a sprite is flipped when rendered.
Definition SpriteAtlas.hpp:38
bool operator==(const SpriteOptions &other) const =default
Compare this set of options to another set for equality.
bool convertToPremultipliedAlpha
Convert the inserted sprite image from straight to pre-multiplied alpha.
Definition SpriteAtlas.hpp:59
FlipAxis
Flag values for Flip that describe how a sprite is flipped when rendered.
Definition SpriteAtlas.hpp:43
@ FLIP_VERTICALLY
Flip the sprite along the Y axis.
Definition SpriteAtlas.hpp:46
@ NO_FLIP
Do not flip the sprite.
Definition SpriteAtlas.hpp:44
@ FLIP_HORIZONTALLY
Flip the sprite along the X axis.
Definition SpriteAtlas.hpp:45
Configuration options for the sampler of a Texture.
Definition Texture.hpp:617
std::size_t operator()(const grem::graphics::SpriteID &spriteID) const
Definition SpriteAtlas.hpp:399