Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
3babca9
feat: Add optional id to BatchItem and methods for managing items by …
gnarhard Jul 21, 2025
c474ad1
refactor: Simplify logic for adding and replacing BatchItems
gnarhard Jul 21, 2025
15942a5
feat: Add tests for new BatchItem ID management functionality
gnarhard Jul 21, 2025
ff42f75
docs: Add documentation about ID management in SpriteBatch section of…
gnarhard Jul 21, 2025
f7e5329
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Jul 21, 2025
a1afe6d
perf: Remove redundant lookup
gnarhard Jul 22, 2025
b843c45
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Jul 22, 2025
1804a88
fix: Add suggested code change to get keys from _idToIndex map keys
gnarhard Jul 27, 2025
5c2752c
fix: Add Free List Strategy for managing indices to prevent race cond…
gnarhard Jul 27, 2025
0c4f4ff
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Aug 4, 2025
8996ede
perf: optimize getting transforms, sources, and colors list while avo…
gnarhard Aug 4, 2025
e964abc
refactor: Rip out id functionality and transform, source, and color l…
gnarhard Aug 6, 2025
05d792b
feat: Add method to retrieve a BatchItem at a given index
gnarhard Aug 16, 2025
33a09db
fix: Update SpriteBatch tests
gnarhard Aug 16, 2025
a06a16b
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Aug 16, 2025
025cd11
docs: Remove ID reference in docs
gnarhard Aug 16, 2025
0b51063
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
spydon Aug 18, 2025
312dda2
Fix formatting
spydon Aug 18, 2025
0c7aace
perf: Move list creation inside if statement that uses those objects
gnarhard Aug 18, 2025
a577478
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
spydon Aug 23, 2025
071e7b2
Merge branch 'feat/manage_sprite_batch_items_by_id' of https://github…
gnarhard Aug 23, 2025
a81322d
refactor: Don't create a new paint reference each render cycle, organ…
gnarhard Aug 23, 2025
39ebfd4
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Aug 23, 2025
69ae8a4
feat: Use a Free List Strategy on BatchItem indexes within SpriteBatc…
gnarhard Jul 21, 2025
0e0479d
Merge branch 'feat/manage_sprite_batch_items_by_id' of https://github…
gnarhard Sep 16, 2025
a9df9e3
perf: add color property to BatchItem to optimize color getting so we…
gnarhard Oct 2, 2025
e29e8b4
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Oct 2, 2025
4c0a9a9
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Oct 3, 2025
b3cda89
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Jan 6, 2026
b7c1541
Update packages/flame/lib/src/sprite_batch.dart
gnarhard Jan 6, 2026
c62b6bb
refactor: Remove test that was providing duplicate functionality: use…
gnarhard Jan 6, 2026
0ff6ee2
fix: Fix tests by preserving old flipping and color semantics and par…
gnarhard Jan 6, 2026
53eb190
Merge branch 'feat/manage_sprite_batch_items_by_id' of https://github…
gnarhard Jan 6, 2026
777a586
chore: Fix lint errors
gnarhard Jan 6, 2026
980f9f0
fix: Fix lint warning from unused local variable
gnarhard Jan 6, 2026
81b7f04
fix: Fix lint warning
gnarhard Jan 6, 2026
6d4cc5e
refactor: Restore removed test
gnarhard Jan 7, 2026
c7d3825
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Jan 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/flame/rendering/images.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,11 @@ A `SpriteBatchComponent` is also available for your convenience.
See how to use it in the
[SpriteBatch examples](https://github.com/flame-engine/flame/blob/main/examples/lib/stories/sprites/sprite_batch_example.dart)

When using a SpriteBatch to render animations, it's helpful to set a unique ID of the `BatchItem`
related to the frame of your animation to make replacing and removing frames more reliable. When
replacing a `BatchItem`, you can use the `findIndexById` to retrieve the associated index
for replacement.


## ImageComposition

Expand Down
204 changes: 152 additions & 52 deletions packages/flame/lib/src/sprite_batch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ class BatchItem {
BatchItem({
required this.source,
required this.transform,
this.id,
Color? color,
this.flip = false,
}) : paint = Paint()..color = color ?? const Color(0x00000000),
destination = Offset.zero & source.size;

/// Optional identifier for the batch item.
final String? id;

/// The source rectangle on the [SpriteBatch.atlas].
final Rect source;

Expand Down Expand Up @@ -144,37 +148,83 @@ class SpriteBatch {

FlippedAtlasStatus _flippedAtlasStatus = FlippedAtlasStatus.none;

/// List of all the existing batch items.
final _batchItems = <BatchItem>[];
/// Stack of available (freed) indices using ListQueue as a stack.
final Queue<int> _freeIndices = Queue<int>();

/// Returns the total number of indices that have been allocated.
int get allocatedCount => _nextIndex;

/// Returns the number of currently free indices.
int get freeCount => _freeIndices.length;

/// The next index to allocate if no free indices are available.
int _nextIndex = 0;

/// A map to keep track of the logical index of each batch item by its id.
final Map<String, int> _idToIndex = {};

/// Returns all current ids
Iterable<String> get ids => _idToIndex.keys;

/// Sparse array of batch items, indexed by allocated indices.
final Map<int, BatchItem> _batchItems = {};

/// Returns the number of indices currently in use.
int get usedCount => _nextIndex - _freeIndices.length;

/// Allocates a new index, reusing freed indices when possible.
int _allocateIndex() {
if (_freeIndices.isNotEmpty) {
return _freeIndices.removeFirst();
}
return _nextIndex++;
}

/// Frees an index to be reused later.
void _freeIndex(int index) {
_freeIndices.addFirst(index);
}

/// The sources to use on the [atlas].
final _sources = <Rect>[];
/// The sources to use on the [atlas], stored sparsely.
final Map<int, Rect> _sources = {};

/// The sources list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add sources use the
/// [add] or [addTransform] method.
UnmodifiableListView<Rect> get sources {
return UnmodifiableListView<Rect>(_sources);
/// Returns a compact list of sources for rendering.
List<Rect> get sources {
final result = <Rect>[];
for (var i = 0; i < _nextIndex; i++) {
if (_sources.containsKey(i)) {
result.add(_sources[i]!);
}
}
return result;
}

/// The transforms that should be applied on the [_sources].
final _transforms = <RSTransform>[];
/// The transforms that should be applied on the [_sources], stored sparsely.
final Map<int, RSTransform> _transforms = {};

/// The transforms list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add transforms use the
/// [add] or [addTransform] method.
UnmodifiableListView<RSTransform> get transforms {
return UnmodifiableListView<RSTransform>(_transforms);
/// Returns a compact list of transforms for rendering.
List<RSTransform> get transforms {
final result = <RSTransform>[];
for (var i = 0; i < _nextIndex; i++) {
if (_transforms.containsKey(i)) {
result.add(_transforms[i]!);
}
}
return result;
}

/// The background color for the [_sources].
final _colors = <Color>[];
/// The background color for the [_sources], stored sparsely.
final Map<int, Color> _colors = {};

/// The colors list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add colors use the
/// [add] or [addTransform] method.
UnmodifiableListView<Color> get colors {
return UnmodifiableListView<Color>(_colors);
/// Returns a compact list of colors for rendering.
List<Color> get colors {
final result = <Color>[];
for (var i = 0; i < _nextIndex; i++) {
if (_colors.containsKey(i)) {
result.add(_colors[i]!);
}
}
return result;
}

/// The atlas used by the [SpriteBatch].
Expand Down Expand Up @@ -243,15 +293,17 @@ class SpriteBatch {
return picture.toImageSafe(image.width * 2, image.height);
}

int get length => _sources.length;
/// Returns the number of active batch items.
int get length => _batchItems.length;

/// Replace provided values of a batch item at the [index], when a parameter
/// is not provided, the original value of the batch item will be used.
///
/// Throws an [ArgumentError] if the [index] is out of bounds.
/// Throws an [ArgumentError] if the [index] doesn't exist.
/// At least one of the parameters must be different from null.
void replace(
int index, {
String? id,
Rect? source,
Color? color,
RSTransform? transform,
Expand All @@ -261,23 +313,27 @@ class SpriteBatch {
'At least one of the parameters must be different from null.',
);

if (index < 0 || index >= length) {
throw ArgumentError('Index out of bounds: $index');
if (!_batchItems.containsKey(index)) {
throw ArgumentError('Index does not exist: $index');
}

final currentBatchItem = _batchItems[index];
final currentBatchItem = _batchItems[index]!;
final newBatchItem = BatchItem(
id: id ?? currentBatchItem.id,
source: source ?? currentBatchItem.source,
transform: transform ?? currentBatchItem.transform,
color: color ?? currentBatchItem.paint.color,
flip: currentBatchItem.flip,
);

_batchItems[index] = newBatchItem;

_sources[index] = newBatchItem.source;
_transforms[index] = newBatchItem.transform;
_colors[index] = color ?? _defaultColor;

if (id != null) {
_idToIndex[id] = index;
}
}

/// Add a new batch item using a RSTransform.
Expand All @@ -295,13 +351,16 @@ class SpriteBatch {
/// cosine of the rotation so that they can be reused over multiple calls to
/// this constructor, it may be more efficient to directly use this method
/// instead.
void addTransform({
int addTransform({
required Rect source,
RSTransform? transform,
bool flip = false,
Color? color,
String? id,
}) {
final index = _allocateIndex();
final batchItem = BatchItem(
id: id,
source: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
Expand All @@ -312,21 +371,25 @@ class SpriteBatch {
_makeFlippedAtlas();
}

_batchItems.add(batchItem);
_sources.add(
flip
? Rect.fromLTWH(
// The atlas is twice as wide when the flipped atlas is generated.
(atlas.width * (_flippedAtlasStatus.isGenerated ? 1 : 2)) -
source.right,
source.top,
source.width,
source.height,
)
: batchItem.source,
);
_transforms.add(batchItem.transform);
_colors.add(color ?? _defaultColor);
_batchItems[index] = batchItem;
_sources[index] = flip
? Rect.fromLTWH(
// The atlas is twice as wide when the flipped atlas is generated.
(atlas.width * (_flippedAtlasStatus.isGenerated ? 1 : 2)) -
source.right,
source.top,
source.width,
source.height,
)
: batchItem.source;
_transforms[index] = batchItem.transform;
_colors[index] = color ?? _defaultColor;

if (id != null) {
_idToIndex[id] = index;
}

return index;
}

/// Add a new batch item.
Expand All @@ -347,8 +410,9 @@ class SpriteBatch {
/// multiple [RSTransform] objects,
/// it may be more efficient to directly use the more direct [addTransform]
/// method instead.
void add({
int add({
required Rect source,
String? id,
double scale = 1.0,
Vector2? anchor,
double rotation = 0,
Expand Down Expand Up @@ -377,20 +441,51 @@ class SpriteBatch {
);
}

addTransform(
return addTransform(
source: source,
transform: transform,
flip: flip,
color: color,
id: id,
);
}

/// Finds the index of the batch item with the given [id].
int? findIndexById(String id) => _idToIndex[id];

/// Removes a batch item by its [id].
void removeById(String id) {
final index = _idToIndex[id];
if (index == null) {
return;
}

removeAt(index);
_idToIndex.remove(id);
}

/// Removes a batch item at the given [index].
void removeAt(int index) {
if (!_batchItems.containsKey(index)) {
throw ArgumentError('Index does not exist: $index');
}

_batchItems.remove(index);
_sources.remove(index);
_transforms.remove(index);
_colors.remove(index);
_freeIndex(index);
}

/// Clear the SpriteBatch so it can be reused.
void clear() {
_sources.clear();
_transforms.clear();
_colors.clear();
_batchItems.clear();
_idToIndex.clear();
_freeIndices.clear();
_nextIndex = 0;
}

// Used to not create new Paint objects in [render] and
Expand All @@ -409,7 +504,11 @@ class SpriteBatch {

final renderPaint = paint ?? _emptyPaint;

final hasNoColors = _colors.every((c) => c == _defaultColor);
final sourcesList = sources;
final transformsList = transforms;
final colorsList = colors;

final hasNoColors = colorsList.every((c) => c == _defaultColor);
final actualBlendMode = blendMode ?? defaultBlendMode;
if (!hasNoColors && actualBlendMode == null) {
throw 'When setting any colors, a blend mode must be provided.';
Expand All @@ -418,15 +517,16 @@ class SpriteBatch {
if (useAtlas && !_flippedAtlasStatus.isGenerating) {
canvas.drawAtlas(
atlas,
_transforms,
_sources,
hasNoColors ? null : _colors,
transformsList,
sourcesList,
hasNoColors ? null : colorsList,
actualBlendMode,
cullRect,
renderPaint,
);
} else {
for (final batchItem in _batchItems) {
for (final index in _batchItems.keys) {
final batchItem = _batchItems[index]!;
renderPaint.blendMode = blendMode ?? renderPaint.blendMode;

canvas
Expand Down
27 changes: 27 additions & 0 deletions packages/flame/test/sprite_batch_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,33 @@ void main() {
);
});

test('can add a batch item with an id', () {
final image = _MockImage();
final spriteBatch = SpriteBatch(image);
spriteBatch.add(source: Rect.zero, id: 'item1');

final batchItem = spriteBatch.findIndexById('item1');

expect(batchItem, isNotNull);
});

test('can replace a batch item with an id', () {
final image = _MockImage();
final spriteBatch = SpriteBatch(image);
spriteBatch.add(source: Rect.zero, id: 'item1');

spriteBatch.replace(
spriteBatch.findIndexById('item1')!,
source: const Rect.fromLTWH(1, 1, 1, 1),
id: 'item2',
);

final batchItem = spriteBatch.findIndexById('item2');

expect(batchItem, isNotNull);
expect(spriteBatch.sources.first, const Rect.fromLTWH(1, 1, 1, 1));
});

const margin = 2.0;
const tileSize = 6.0;

Expand Down