diff --git a/CHANGELOG.md b/CHANGELOG.md index 7808248ef..5a376c26c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ Arcade [PyPi Release History](https://pypi.org/project/arcade/#history) page. - Sped up `arcade.Text` updates. Setting a property to the value it already has no longer lays out the text again (for example `font_size`, `bold`, or `width` went from about 165 µs to under 1 µs), and a `with text:` block only lays out the text if something in it needs a new layout. An unchanged `arcade.TextPool` frame with 5 lines went from 760 µs to 6 µs. - Added a "Drawing Text" page to the programming guide: choosing between `draw_text`, `Text`, `TextPool`, and `create_text_sprite`, what's slow and fast to change, batches, fonts (names, font files, and the bundled Kenney and Liberation fonts), and styles. Updated the text section of the performance tips, and the `draw_text` warning and docstring, which overstated how slow it is. - Tile maps no longer use Pillow's `Image.getdata()`, which is deprecated and will be removed in Pillow 14, to apply an image layer's transparent color. It's done with Pillow operations instead, which is also faster (a 1024x600 image went from 76 ms to 4 ms). +- Sped up removing many sprites from a large `SpriteList`, such as every bullet that hit something this frame. `SpriteList.remove()`, and so `Sprite.remove_from_sprite_lists()` and `kill()`, used to search the whole list for each sprite. Removals now wait until the list is next used, and many are applied in one pass: removing 100 sprites from 41,000 went from 19 ms to 3.3 ms, and 500 from 166,000 went from 630 ms to 17 ms. Drawing order is kept, and a few removals cost the same as before. ## 4.0.0.dev8 diff --git a/arcade/sprite_list/sprite_list.py b/arcade/sprite_list/sprite_list.py index c32d55802..76ff53527 100644 --- a/arcade/sprite_list/sprite_list.py +++ b/arcade/sprite_list/sprite_list.py @@ -11,6 +11,7 @@ import struct from abc import abstractmethod from array import array +from itertools import filterfalse from collections import deque from collections.abc import Callable, Collection, Iterable, Iterator, Sized from typing import ( @@ -33,6 +34,11 @@ from arcade.texture_atlas import TextureAtlasBase +# With this many sprites or more removed from a SpriteList at once, one pass +# over the list is faster than finding each sprite in it +_REMOVE_IN_ONE_PASS = 8 + + def _align_capacity(capacity: int) -> int: """ Aligns the capacity to be a multiple of 256. @@ -265,8 +271,12 @@ def __init__( # List of free slots in the sprite buffers. These are filled when sprites are removed. self._sprite_buffer_free_slots: deque[int] = deque() - # List of sprites in the sprite list - self.sprite_list: list[SpriteType] = [] + # List of sprites in the sprite list. Read it through the sprite_list + # property, which applies pending removals first. + self._sprite_list: list[SpriteType] = [] + # Sprites removed but still in _sprite_list and the index buffer, + # with their buffer slots. See remove(). + self._pending_removals: dict[SpriteType, int] = {} # Buffer slots for the sprites (excluding index buffer) # This has nothing to do with the index in the spritelist itself self.sprite_slot: dict[SpriteType, int] = dict() @@ -308,6 +318,55 @@ def __init__( except RuntimeError: pass + @property + def sprite_list(self) -> list[SpriteType]: + """The sprites in the list, in drawing order.""" + if self._pending_removals: + self._apply_removals() + return self._sprite_list + + @sprite_list.setter + def sprite_list(self, sprites: list[SpriteType]) -> None: + if self._pending_removals: + self._apply_removals() + self._sprite_list = sprites + + def _apply_removals(self) -> None: + """ + Take the sprites removed with remove() out of the sprite list and + the index buffer, keeping the order of the rest. + + Finding a sprite in the list is ``O(N)``, so removing many sprites + one at a time costs ``O(N)`` each. A few are removed that way, but + more are removed with a single pass over the list. + """ + pending = self._pending_removals + self._pending_removals = {} + sprites = self._sprite_list + index_data = self._sprite_index_data + + if len(pending) < _REMOVE_IN_ONE_PASS: + for sprite in pending: + index = sprites.index(sprite) + sprites.pop(index) + index_data.pop(index) + index_data.append(0) + else: + # The removed sprites' buffer slots aren't reused until below, so + # they still mark where the sprites are in the index buffer + removed_slots = set(pending.values()) + count = len(sprites) + self._sprite_list = list(filterfalse(pending.__contains__, sprites)) + index_data = array("I", filterfalse(removed_slots.__contains__, index_data[:count])) + index_data.extend([0] * (self._idx_capacity - len(index_data))) + self._sprite_index_data = index_data + + # Only now can the buffer slots be reused, since the index buffer + # pointed at them until now + self._sprite_buffer_free_slots.extend(pending.values()) + self._sprite_index_slots -= len(pending) + self._sprite_index_changed = True + def _init_deferred(self) -> None: """ Since spritelist can be created before the window we need to defer initialization. @@ -641,6 +700,8 @@ def append(self, sprite: SpriteType) -> None: """ if sprite in self.sprite_slot: raise ValueError("Sprite already in SpriteList") + if self._pending_removals: + self._apply_removals() slot = self._next_slot() self.sprite_slot[sprite] = slot @@ -695,9 +756,10 @@ def remove(self, sprite: SpriteType) -> None: """ Remove a specific sprite from the list. - Note that this method is ``O(N)`` in complexity and will have - and increased cost the more sprites you have in the list. - A faster option is to use :py:meth:`pop` or :py:meth:`swap`. + The sprite is removed right away, but taking it out of the list's + internal storage waits until the list is next used, so many + sprites removed together, such as every bullet that hit something + this frame, are taken out in one pass instead of one at a time. Args: sprite: Item to remove from the list @@ -707,17 +769,9 @@ def remove(self, sprite: SpriteType) -> None: except KeyError: raise ValueError("Sprite is not in the SpriteList") - index = self.sprite_list.index(sprite) - self.sprite_list.pop(index) sprite._unregister_sprite_list(self) del self.sprite_slot[sprite] - - self._sprite_buffer_free_slots.append(slot) - - self._sprite_index_data.pop(index) - self._sprite_index_data.append(0) - self._sprite_index_slots -= 1 - self._sprite_index_changed = True + self._pending_removals[sprite] = slot if self.spatial_hash is not None: self.spatial_hash.remove(sprite) @@ -940,6 +994,8 @@ def write_sprite_buffers_to_gpu(self) -> None: def _write_sprite_buffers_to_gpu(self) -> None: if not self._initialized: self._init_deferred() + if self._pending_removals: + self._apply_removals() self.data.write_sprite_buffers_to_gpu( # Buffer data diff --git a/tests/unit/spritelist/test_spritelist_deferred_remove.py b/tests/unit/spritelist/test_spritelist_deferred_remove.py new file mode 100644 index 000000000..16c2e475f --- /dev/null +++ b/tests/unit/spritelist/test_spritelist_deferred_remove.py @@ -0,0 +1,214 @@ +""" +SpriteList.remove() takes sprites out of the list's storage later, when the +list is next used, so many removals are applied in one pass. These tests +check the list behaves as if each removal happened right away. +""" + +import random +import struct + +import pytest + +import arcade +from arcade.sprite_list import sprite_list as sprite_list_module + +# Fewer than this many removals are applied one at a time, more in one pass +ONE_PASS = getattr(sprite_list_module, "_REMOVE_IN_ONE_PASS", 8) +COUNTS = [1, ONE_PASS - 1, ONE_PASS, 40] + + +def _make(count, use_spatial_hash=False): + sprites = arcade.SpriteList(use_spatial_hash=use_spatial_hash) + for i in range(count): + sprite = arcade.SpriteSolidColor(4, 4, center_x=i * 5, center_y=10) + sprite.name = i + sprites.append(sprite) + return sprites + + +def _drawn_sprites(spritelist): + """The sprites the GPU will draw, in order, read back from the GPU index buffer""" + spritelist.draw() + count = spritelist._sprite_index_slots + gpu_slots = struct.unpack(f"{count}I", spritelist.data.storage_index.read()[: count * 4]) + sprite_for_slot = {slot: sprite for sprite, slot in spritelist.sprite_slot.items()} + return [sprite_for_slot.get(slot) for slot in gpu_slots] + + +def _check(spritelist, expected): + """The list, its bookkeeping, and the GPU draw order all match ``expected``""" + assert list(spritelist) == expected + assert len(spritelist) == len(expected) + assert [spritelist[i] for i in range(len(expected))] == expected + assert all(spritelist.index(sprite) == i for i, sprite in enumerate(expected)) + assert set(spritelist.sprite_slot) == set(expected) + slots = [spritelist.sprite_slot[sprite] for sprite in expected] + assert len(set(slots)) == len(slots) + assert not set(slots) & set(spritelist._sprite_buffer_free_slots) + assert _drawn_sprites(spritelist) == expected + + +@pytest.mark.parametrize("count", COUNTS) +def test_remove_keeps_order(ctx, count): + spritelist = _make(60) + spritelist.draw() + sprites = list(spritelist) + removed = random.Random(count).sample(sprites, count) + for sprite in removed: + sprite.remove_from_sprite_lists() + _check(spritelist, [sprite for sprite in sprites if sprite not in removed]) + + +@pytest.mark.parametrize("count", COUNTS) +def test_removed_sprite_is_gone_right_away(ctx, count): + spritelist = _make(60, use_spatial_hash=True) + removed = list(spritelist)[:count] + for sprite in removed: + spritelist.remove(sprite) + assert sprite not in spritelist + assert sprite.sprite_lists == [] + # Collisions don't find it, even before the list is used again + assert sprite not in arcade.check_for_collision_with_list(sprite, spritelist) + with pytest.raises(ValueError): + spritelist.remove(removed[0]) + + +@pytest.mark.parametrize("count", COUNTS) +def test_new_sprites_reuse_slots(ctx, count): + """Sprites added after removals can get the removed sprites' buffer slots""" + spritelist = _make(60) + spritelist.draw() + sprites = list(spritelist) + for sprite in sprites[:count]: + sprite.remove_from_sprite_lists() + added = list(_make(count)) + for sprite in added: + sprite.remove_from_sprite_lists() + spritelist.append(sprite) + _check(spritelist, sprites[count:] + added) + + +@pytest.mark.parametrize("count", COUNTS) +def test_remove_and_add_back(ctx, count): + """A removed sprite added back before the list is used again moves to the end""" + spritelist = _make(60) + sprites = list(spritelist) + removed = sprites[10 : 10 + count] + for sprite in removed: + spritelist.remove(sprite) + expected = [sprite for sprite in sprites if sprite not in removed] + spritelist.append(removed[0]) + expected.append(removed[0]) + if count > 1: + spritelist.insert(0, removed[-1]) + expected.insert(0, removed[-1]) + _check(spritelist, expected) + + +@pytest.mark.parametrize("count", COUNTS) +@pytest.mark.parametrize( + "operation", + ["pop", "pop_first", "insert", "swap", "setitem", "reverse", "sort", "shuffle", "clear"], +) +def test_operations_after_removals(ctx, count, operation): + """Every list operation sees the removals""" + spritelist = _make(60) + spritelist.draw() + sprites = list(spritelist) + for sprite in sprites[5 : 5 + count]: + sprite.remove_from_sprite_lists() + expected = sprites[:5] + sprites[5 + count :] + + if operation == "pop": + assert spritelist.pop() is expected.pop() + elif operation == "pop_first": + assert spritelist.pop(0) is expected.pop(0) + elif operation == "insert": + new = arcade.SpriteSolidColor(4, 4) + spritelist.insert(3, new) + expected.insert(3, new) + elif operation == "swap": + spritelist.swap(1, -1) + expected[1], expected[-1] = expected[-1], expected[1] + elif operation == "setitem": + new = arcade.SpriteSolidColor(4, 4) + spritelist[2] = new + expected[2] = new + elif operation == "reverse": + spritelist.reverse() + expected.reverse() + elif operation == "sort": + spritelist.sort(key=lambda sprite: -sprite.name) + expected.sort(key=lambda sprite: -sprite.name) + elif operation == "shuffle": + spritelist.shuffle() + # Any order of the same sprites, as long as the GPU draws that order + assert sorted(spritelist, key=lambda sprite: sprite.name) == expected + expected = list(spritelist) + elif operation == "clear": + spritelist.clear() + expected = [] + _check(spritelist, expected) + + +def test_many_rounds_of_removing_and_adding(ctx): + """Random removals and additions over many frames stay consistent""" + rng = random.Random(7) + spritelist = _make(200) + expected = list(spritelist) + for frame in range(30): + for sprite in rng.sample(expected, rng.randrange(0, 25)): + sprite.remove_from_sprite_lists() + expected.remove(sprite) + for _ in range(rng.randrange(0, 25)): + sprite = arcade.SpriteSolidColor(4, 4) + sprite.name = frame + spritelist.append(sprite) + expected.append(sprite) + if frame % 3 == 0: + _check(spritelist, expected) + _check(spritelist, expected) + + +def test_removed_sprites_are_not_drawn(window): + """Only the sprites left are drawn""" + spritelist = arcade.SpriteList() + red = arcade.SpriteSolidColor(20, 20, center_x=15, center_y=15, color=arcade.color.RED) + blues = [ + arcade.SpriteSolidColor(20, 20, center_x=15, center_y=15, color=arcade.color.BLUE) + for _ in range(ONE_PASS + 2) + ] + spritelist.append(red) + spritelist.extend(blues) + window.clear() + spritelist.draw() + assert arcade.get_pixel(15, 15) == arcade.color.BLUE[:3] + + for blue in blues: + blue.remove_from_sprite_lists() + window.clear() + spritelist.draw() + assert arcade.get_pixel(15, 15) == arcade.color.RED[:3] + + +class _CountingList(list): + """A list that counts searches, which cost O(N) each""" + + searches = 0 + + def index(self, *args): + type(self).searches += 1 + return super().index(*args) + + +@pytest.mark.parametrize(("count", "searches"), [(ONE_PASS - 1, ONE_PASS - 1), (40, 0)]) +def test_many_removals_dont_search_for_each_sprite(ctx, count, searches): + """A few removals find each sprite, but many are applied in one pass""" + spritelist = _make(60) + _CountingList.searches = 0 + spritelist.sprite_list = _CountingList(spritelist.sprite_list) + sprites = list(spritelist) + for sprite in sprites[:count]: + sprite.remove_from_sprite_lists() + assert len(spritelist) == 60 - count + assert _CountingList.searches == searches