Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 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
139 changes: 78 additions & 61 deletions packages/flame/lib/src/sprite_batch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -156,37 +156,35 @@ 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>();

/// The sources to use on the [atlas].
final _sources = <Rect>[];
/// Returns the total number of indices that have been allocated.
int get allocatedCount => _nextIndex;

/// 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 the number of currently free indices.
int get freeCount => _freeIndices.length;

/// The transforms that should be applied on the [_sources].
final _transforms = <RSTransform>[];
/// The next index to allocate if no free indices are available.
int _nextIndex = 0;

/// 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);
}
/// Sparse array of batch items, indexed by allocated indices.
final Map<int, BatchItem> _batchItems = {};

/// The background color for the [_sources].
final _colors = <Color>[];
/// 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++;
}

/// 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);
/// Frees an index to be reused later.
void _freeIndex(int index) {
_freeIndices.addFirst(index);
}

/// The atlas used by the [SpriteBatch].
Expand Down Expand Up @@ -255,12 +253,13 @@ 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, {
Expand All @@ -273,11 +272,11 @@ 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(
source: source ?? currentBatchItem.source,
transform: transform ?? currentBatchItem.transform,
Expand All @@ -286,10 +285,14 @@ class SpriteBatch {
);

_batchItems[index] = newBatchItem;
}

_sources[index] = newBatchItem.source;
_transforms[index] = newBatchItem.transform;
_colors[index] = color ?? _defaultColor;
/// Returns the [BatchItem] at the given [index].
BatchItem getBatchItem(int index) {
if (!_batchItems.containsKey(index)) {
throw ArgumentError('Index does not exist: $index');
}
return _batchItems[index]!;
}

/// Add a new batch item using a RSTransform.
Expand All @@ -307,26 +310,15 @@ 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,
}) {
final index = _allocateIndex();
final batchItem = BatchItem(
source: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
color: color ?? defaultColor,
);

if (flip && useAtlas && _flippedAtlasStatus.isNone) {
_makeFlippedAtlas();
}

_batchItems.add(batchItem);
_sources.add(
flip
source: flip
? Rect.fromLTWH(
// The atlas is twice as wide when the flipped atlas is generated.
(atlas.width * (_flippedAtlasStatus.isGenerated ? 1 : 2)) -
Expand All @@ -335,10 +327,19 @@ class SpriteBatch {
source.width,
source.height,
)
: batchItem.source,
: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
color: color ?? defaultColor,
);
_transforms.add(batchItem.transform);
_colors.add(color ?? _defaultColor);

if (flip && useAtlas && _flippedAtlasStatus.isNone) {
_makeFlippedAtlas();
}

_batchItems[index] = batchItem;

return index;
}

/// Add a new batch item.
Expand All @@ -359,7 +360,7 @@ 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,
double scale = 1.0,
Vector2? anchor,
Expand Down Expand Up @@ -389,20 +390,29 @@ class SpriteBatch {
);
}

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

/// 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);
_freeIndex(index);
}

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

// Used to not create new Paint objects in [render] and
Expand All @@ -420,8 +430,14 @@ class SpriteBatch {
}

final renderPaint = paint ?? _emptyPaint;

final hasNoColors = _colors.every((c) => c == _defaultColor);
final transforms =
_batchItems.values.map((e) => e.transform).toList(growable: false);
final sources =
_batchItems.values.map((e) => e.source).toList(growable: false);
final colors =
_batchItems.values.map((e) => e.paint.color).toList(growable: false);

final hasNoColors = colors.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 @@ -430,15 +446,16 @@ class SpriteBatch {
if (useAtlas && !_flippedAtlasStatus.isGenerating) {
canvas.drawAtlas(
atlas,
_transforms,
_sources,
hasNoColors ? null : _colors,
transforms,
sources,
hasNoColors ? null : colors,
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
21 changes: 13 additions & 8 deletions packages/flame/test/sprite_batch_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ void main() {
test('can add to the batch', () {
final image = _MockImage();
final spriteBatch = SpriteBatch(image);
spriteBatch.add(source: Rect.zero);
final index = spriteBatch.add(source: Rect.zero);

expect(spriteBatch.transforms, hasLength(1));
expect(spriteBatch.getBatchItem(index), isNotNull);
});

test('can replace the color of a batch', () {
Expand All @@ -28,8 +28,13 @@ void main() {

spriteBatch.replace(0, color: Colors.red);

expect(spriteBatch.colors, hasLength(1));
expect(spriteBatch.colors.first, Colors.red);
final batchItem = spriteBatch.getBatchItem(0);

/// Use .closeTo() to avoid floating point rounding errors.
expect(batchItem.paint.color.a, closeTo(Colors.red.a, 0.001));
expect(batchItem.paint.color.r, closeTo(Colors.red.r, 0.001));
expect(batchItem.paint.color.g, closeTo(Colors.red.g, 0.001));
expect(batchItem.paint.color.b, closeTo(Colors.red.b, 0.001));
});

test('can replace the source of a batch', () {
Expand All @@ -38,9 +43,9 @@ void main() {
spriteBatch.add(source: Rect.zero);

spriteBatch.replace(0, source: const Rect.fromLTWH(1, 1, 1, 1));
final batchItem = spriteBatch.getBatchItem(0);

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

test('can replace the transform of a batch', () {
Expand All @@ -49,10 +54,10 @@ void main() {
spriteBatch.add(source: Rect.zero);

spriteBatch.replace(0, transform: RSTransform(1, 1, 1, 1));
final batchItem = spriteBatch.getBatchItem(0);

expect(spriteBatch.transforms, hasLength(1));
expect(
spriteBatch.transforms.first,
batchItem.transform,
isA<RSTransform>()
.having((t) => t.scos, 'scos', 1)
.having((t) => t.ssin, 'ssin', 1)
Expand Down
Loading