-
-
Notifications
You must be signed in to change notification settings - Fork 1k
feat: Add object pooling support with Poolable mixin and ComponentPool
#3816
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ufrshubham
wants to merge
9
commits into
main
Choose a base branch
from
devkage/object-pooling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8c80eca
Add `ComponentPool` and `Poolable` mixin for reusable components
ufrshubham 413f6ea
Expose `maxSize` and add `availableCount`
ufrshubham dd08b49
Add tests for ComponentPool and Poolable
ufrshubham 20eb2ec
Export component pool and poolable mixin
ufrshubham 0ec10fa
Add object pooling section to performance docs
ufrshubham f4dcb6a
Add Component Pool example
ufrshubham 29a4054
Add 'Poolable' to CSpell flame dictionary
ufrshubham 4413736
Remove trailing whitespace in ComponentPool comments
ufrshubham 7050990
Fix analyze issues
ufrshubham File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
173 changes: 173 additions & 0 deletions
173
examples/lib/stories/components/component_pool_example.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| import 'dart:math'; | ||
|
|
||
| import 'package:flame/components.dart'; | ||
| import 'package:flame/events.dart'; | ||
| import 'package:flame/game.dart'; | ||
| import 'package:flutter/material.dart'; | ||
|
|
||
| class ComponentPoolExample extends FlameGame { | ||
| static const String description = | ||
| 'Tap on the screen to spawn a burst of pooled bullets. ' | ||
| 'Watch the stats to see active vs pooled bullets and observe ' | ||
| 'how the pool efficiently reuses objects.'; | ||
|
|
||
| static const gameWidth = 800.0; | ||
| static const gameHeight = 600.0; | ||
|
|
||
| ComponentPoolExample() | ||
| : super( | ||
| world: _BulletWorld(), | ||
| camera: CameraComponent.withFixedResolution( | ||
| width: gameWidth, | ||
| height: gameHeight, | ||
| ), | ||
| ) { | ||
| camera.moveTo(Vector2(gameWidth / 2, gameHeight / 2)); | ||
| } | ||
| } | ||
|
|
||
| class _BulletWorld extends World with TapCallbacks { | ||
| late final ComponentPool<_PooledBullet> bulletPool; | ||
| late final _StatsDisplay statsDisplay; | ||
| final Random _random = Random(); | ||
|
|
||
| static const bulletsPerTap = 12; | ||
|
|
||
| @override | ||
| Future<void> onLoad() async { | ||
| // Add a background | ||
| add( | ||
| RectangleComponent( | ||
| size: Vector2( | ||
| ComponentPoolExample.gameWidth, | ||
| ComponentPoolExample.gameHeight, | ||
| ), | ||
| paint: Paint()..color = Colors.green, | ||
| ), | ||
| ); | ||
|
|
||
| // Create a pool with a larger initial size to handle bursts | ||
| // and a maximum size to accommodate multiple bullet bursts | ||
| bulletPool = ComponentPool<_PooledBullet>( | ||
| factory: _PooledBullet.new, | ||
| initialSize: 30, | ||
| maxSize: 200, | ||
| ); | ||
|
|
||
| // Add a stats display to show pool information | ||
| statsDisplay = _StatsDisplay(pool: bulletPool); | ||
| await add(statsDisplay); | ||
| } | ||
|
|
||
| @override | ||
| void onTapDown(TapDownEvent event) { | ||
| final tapPosition = event.localPosition; | ||
|
|
||
| for (var i = 0; i < bulletsPerTap; i++) { | ||
| final bullet = bulletPool.acquire(); | ||
| bullet.position.setFrom(tapPosition); | ||
|
|
||
| // Create a spread pattern - bullets go out in all directions | ||
| final angle = (i / bulletsPerTap) * 2 * pi; | ||
| final speed = 150.0 + _random.nextDouble() * 100; | ||
| bullet.velocity = Vector2(cos(angle) * speed, sin(angle) * speed); | ||
|
|
||
| // Add slight random variation to velocity | ||
| bullet.velocity.add( | ||
| Vector2( | ||
| (_random.nextDouble() - 0.5) * 30, | ||
| (_random.nextDouble() - 0.5) * 30, | ||
| ), | ||
| ); | ||
|
|
||
| add(bullet); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// A simple bullet component that can be pooled. | ||
| class _PooledBullet extends CircleComponent | ||
| with Poolable, HasGameReference, ParentIsA<_BulletWorld> { | ||
| Vector2 velocity = Vector2.zero(); | ||
|
|
||
| _PooledBullet() | ||
| : super( | ||
| radius: 4, | ||
| paint: Paint() | ||
| ..color = Colors.yellowAccent | ||
| ..style = PaintingStyle.fill, | ||
| ); | ||
|
|
||
| @override | ||
| void reset() { | ||
| // Reset all properties to their initial state | ||
| position.setZero(); | ||
| velocity.setZero(); | ||
| angle = 0; | ||
| } | ||
|
|
||
| @override | ||
| void update(double dt) { | ||
| position.add(velocity * dt); | ||
|
|
||
| // Check if bullet is outside the game bounds | ||
| final isOutOfBounds = | ||
| position.x < 0 || | ||
| position.x > ComponentPoolExample.gameWidth || | ||
| position.y < 0 || | ||
| position.y > ComponentPoolExample.gameHeight; | ||
|
|
||
| if (isOutOfBounds) { | ||
| parent.bulletPool.release(this); | ||
| } | ||
| } | ||
|
|
||
| @override | ||
| void render(Canvas canvas) { | ||
| // Draw a glow effect | ||
| final glowPaint = Paint() | ||
| ..color = Colors.black.withValues(alpha: 0.3) | ||
| ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3); | ||
| canvas.drawCircle(Offset.zero, radius * 2, glowPaint); | ||
|
|
||
| // Draw the main bullet | ||
| super.render(canvas); | ||
| } | ||
| } | ||
|
|
||
| /// Displays statistics about the bullet pool. | ||
| class _StatsDisplay extends TextComponent with ParentIsA<_BulletWorld> { | ||
| final ComponentPool<_PooledBullet> pool; | ||
| int _activeBullets = 0; | ||
|
|
||
| _StatsDisplay({required this.pool}) | ||
| : super( | ||
| position: Vector2(10, 10), | ||
| textRenderer: TextPaint( | ||
| style: const TextStyle( | ||
| color: Colors.white, | ||
| fontSize: 14, | ||
| fontWeight: FontWeight.bold, | ||
| shadows: [ | ||
| Shadow( | ||
| offset: Offset(1, 1), | ||
| blurRadius: 2, | ||
| ), | ||
| ], | ||
| ), | ||
| ), | ||
| ); | ||
|
|
||
| @override | ||
| void update(double dt) { | ||
| super.update(dt); | ||
|
|
||
| // Count active bullets (in the world but not in the pool) | ||
| _activeBullets = parent.children.whereType<_PooledBullet>().length; | ||
|
|
||
| text = | ||
| 'Active Bullets: $_activeBullets\n' | ||
| 'In Pool (Ready): ${pool.availableCount}\n' | ||
| '\nTap to spawn ${_BulletWorld.bulletsPerTap} bullets!'; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Couldn't we just tell the users to do this in
onMount, then we don't need a new method?