using System;
using System.Collections;
using System.Collections.Generic;
using DotSDL.Interop.Core;
namespace DotSDL.Graphics {
///
/// Represents a collection of objects.
///
public class SpriteList : IList {
private readonly IntPtr _renderer;
private readonly List _sprites = new List();
/// Retrieves the number of objects contained in this .
public int Count => _sprites.Count;
/// Indicates whether or not this is read-only.
public bool IsReadOnly => false;
///
public Sprite this[int index] {
get => _sprites[index];
set {
DestroySprite(_sprites[index]);
InitializeSprite(value);
_sprites[index] = value;
}
}
///
/// Creates a new .
///
/// The SDL2 rendering context that should be used.
public SpriteList(IntPtr renderer) {
_renderer = renderer;
}
///
/// Adds a to this .
///
/// The to add.
public void Add(Sprite item) {
InitializeSprite(item);
_sprites.Add(item);
}
///
/// Removes all items from this .
///
public void Clear() {
_sprites.ForEach(DestroySprite);
_sprites.Clear();
}
///
/// Determines whether this contains a particular instance
/// of a .
///
/// The instance to look for.
/// true if the instance in was found, otherwise false.
public bool Contains(Sprite item) => _sprites.Contains(item);
///
/// Copies the eleents on this into an array, starting at
/// index .
///
/// The array to copy this into.
/// The intex to start copying from.
public void CopyTo(Sprite[] array, int arrayIndex) => _sprites.CopyTo(array, arrayIndex);
///
/// Frees the texture used by a sprite prior to removing it from the list.
///
/// The to destroy.
private void DestroySprite(Canvas sprite) {
Render.DestroyTexture(sprite.Texture);
}
///
public IEnumerator GetEnumerator() => _sprites.GetEnumerator();
///
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
///
/// Creates a texture for a prior to adding it to the list.
///
/// The that needs to be initialized.
private void InitializeSprite(Canvas sprite) {
sprite.Renderer = _renderer;
sprite.CreateTexture();
sprite.UpdateTexture();
}
///
/// Removes a from this .
///
/// The to remove.
/// true if the was successfully removed, otherwise false.
public bool Remove(Sprite item) {
DestroySprite(item);
return _sprites.Remove(item);
}
///
/// Determines the index of a specific ionstnace in the .
///
/// The instance to locate.
/// The index of the instance referenced by if it's been found in the list, otherwise -1.
public int IndexOf(Sprite item) => _sprites.IndexOf(item);
///
/// Inserts a into the at the specified index.
///
/// The zero-based index at which should be inserted.
/// The to insert into the list.
public void Insert(int index, Sprite item) {
InitializeSprite(item);
_sprites.Insert(index, item);
}
///
/// Removes the contained at the specified index from this .
///
/// The zero-based index of the to remove.
public void RemoveAt(int index) {
DestroySprite(_sprites[index]);
_sprites.RemoveAt(index);
}
}
}