Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
27 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
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
71 changes: 70 additions & 1 deletion 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,6 +148,12 @@ class SpriteBatch {

FlippedAtlasStatus _flippedAtlasStatus = FlippedAtlasStatus.none;

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

/// Returns all ids currently in the batch (excluding nulls).
Iterable<String> get ids => _batchItems.map((item) => item.id!);

/// List of all the existing batch items.
final _batchItems = <BatchItem>[];

Expand Down Expand Up @@ -252,6 +262,7 @@ class SpriteBatch {
/// 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 @@ -267,17 +278,23 @@ class SpriteBatch {

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) {
return;
}

_idToIndex[id] = index;
}

/// Add a new batch item using a RSTransform.
Expand All @@ -300,8 +317,10 @@ class SpriteBatch {
RSTransform? transform,
bool flip = false,
Color? color,
String? id,
}) {
final batchItem = BatchItem(
id: id,
source: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
Expand All @@ -327,6 +346,13 @@ class SpriteBatch {
);
_transforms.add(batchItem.transform);
_colors.add(color ?? _defaultColor);

if (id == null) {
return;
}

final newIdx = _batchItems.length - 1;
_idToIndex[id] = newIdx;
}

/// Add a new batch item.
Expand All @@ -349,6 +375,7 @@ class SpriteBatch {
/// method instead.
void add({
required Rect source,
String? id,
double scale = 1.0,
Vector2? anchor,
double rotation = 0,
Expand Down Expand Up @@ -382,15 +409,57 @@ class SpriteBatch {
transform: transform,
flip: flip,
color: color,
id: id,
);
}

/// Finds the index of the batch item with the given [id].
int? findIndexById(String id) {
if (_idToIndex.containsKey(id)) {
return _idToIndex[id];
}
for (var i = 0; i < _batchItems.length; i++) {
if (_batchItems[i].id == id) {
_idToIndex[id] = i; // repair mapping
return i;
}
}
return null;
}

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

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

// adjust indices > removed index
_idToIndex.updateAll((key, idx) => idx > index ? idx - 1 : idx);
}

/// Removes a batch item at the given [index].
void removeAt(int index) {
if (index < 0 || index >= length) {
throw ArgumentError('Index out of bounds: $index');
}

_batchItems.removeAt(index);
_sources.removeAt(index);
_transforms.removeAt(index);
_colors.removeAt(index);
}

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

// Used to not create new Paint objects in [render] and
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