Merge branch 'develop' into feature/serialization

This commit is contained in:
Christian Treffs 2020-10-21 07:32:06 +02:00
commit c88fe2c419
No known key found for this signature in database
GPG Key ID: 49A4B4B460BE3ED4
16 changed files with 410 additions and 136 deletions

View File

@ -76,6 +76,6 @@ jobs:
- name: Swift version - name: Swift version
run: swift --version run: swift --version
- name: Build - name: Build
uses: swiftwasm/swiftwasm-action@master uses: swiftwasm/swiftwasm-action@main
with: with:
shell-action: swift build --triple wasm32-unknown-wasi shell-action: swift build --triple wasm32-unknown-wasi

View File

@ -35,7 +35,7 @@ import PackageDescription
let package = Package( let package = Package(
name: "YourPackageName", name: "YourPackageName",
dependencies: [ dependencies: [
.package(url: "https://github.com/fireblade-engine/ecs.git", from: "0.17.0") .package(url: "https://github.com/fireblade-engine/ecs.git", from: "0.17.3")
], ],
targets: [ targets: [
.target( .target(

View File

@ -8,12 +8,12 @@
extension Entity { extension Entity {
@inlinable @inlinable
public func get<C>() -> C? where C: Component { public func get<C>() -> C? where C: Component {
nexus.get(for: identifier) nexus.get(safe: identifier)
} }
@inlinable @inlinable
public func get<A>(component compType: A.Type = A.self) -> A? where A: Component { public func get<A>(component compType: A.Type = A.self) -> A? where A: Component {
nexus.get(for: identifier) nexus.get(safe: identifier)
} }
@inlinable @inlinable
@ -32,22 +32,124 @@ extension Entity {
return (compA, compB, compC) return (compA, compB, compC)
} }
/// Get or set component instance by type via subscript.
///
/// **Behavior:**
/// - If `Comp` is a component type that is currently *not* assigned to this entity,
/// the new instance will be assigned to this entity.
/// - If `Comp` is already assinged to this entity nothing happens.
/// - If `Comp` is set to `nil` and an instance of `Comp` is assigned to this entity,
/// `Comp` will be removed from this entity.
@inlinable @inlinable
public subscript<C: Component, Value>(_ componentKeyPath: WritableKeyPath<C, Value>) -> Value? { public subscript<Comp>(_ componentType: Comp.Type) -> Comp? where Comp: Component {
get { self.get(component: componentType) }
nonmutating set { nonmutating set {
guard var comp = self.get(component: C.self), guard let newComponent = newValue else {
let value = newValue else { self.remove(Comp.self)
return return
} }
comp[keyPath: componentKeyPath] = value if self.get(component: componentType) === newComponent {
return
} }
get { self.assign(newComponent)
self.get(component: C.self)?[keyPath: componentKeyPath]
} }
} }
/// Get the value of a component using the key Path to the property in the component.
///
/// A `Comp` instance must be assigned to this entity!
/// - Parameter componentKeyPath: The `KeyPath` to the property of the given component.
@inlinable @inlinable
public subscript<C: Component>(_ componentType: C.Type) -> C? { public func get<Comp, Value>(valueAt componentKeyPath: KeyPath<Comp, Value>) -> Value where Comp: Component {
self.get(component: componentType) self.get(component: Comp.self)![keyPath: componentKeyPath]
}
/// Get the value of a component using the key Path to the property in the component.
///
/// A `Comp` instance must be assigned to this entity!
/// - Parameter componentKeyPath: The `KeyPath` to the property of the given component.
@inlinable
public func get<Comp, Value>(valueAt componentKeyPath: KeyPath<Comp, Value?>) -> Value? where Comp: Component {
self.get(component: Comp.self)![keyPath: componentKeyPath]
}
/// Get the value of a component using the key Path to the property in the component.
@inlinable
public subscript<Comp, Value>(_ componentKeyPath: KeyPath<Comp, Value>) -> Value where Comp: Component {
self.get(valueAt: componentKeyPath)
}
/// Get the value of a component using the key Path to the property in the component.
@inlinable
public subscript<Comp, Value>(_ componentKeyPath: KeyPath<Comp, Value?>) -> Value? where Comp: Component {
self.get(valueAt: componentKeyPath)
}
/// Set the value of a component using the key path to the property in the component.
///
/// **Behavior:**
/// - If `Comp` is a component type that is currently *not* assigned to this entity,
/// a new instance of `Comp` will be default initialized and `newValue` will be set at the given keyPath.
///
/// - Parameters:
/// - newValue: The value to set.
/// - componentKeyPath: The `ReferenceWritableKeyPath` to the property of the given component.
/// - Returns: Returns true if an action was performed, false otherwise.
@inlinable
@discardableResult
public func set<Comp, Value>(value newValue: Value, for componentKeyPath: ReferenceWritableKeyPath<Comp, Value>) -> Bool where Comp: Component & DefaultInitializable {
guard has(Comp.self) else {
let newInstance = Comp()
newInstance[keyPath: componentKeyPath] = newValue
return nexus.assign(component: newInstance, entityId: identifier)
}
get(component: Comp.self)![keyPath: componentKeyPath] = newValue
return true
}
/// Set the value of a component using the key path to the property in the component.
///
/// **Behavior:**
/// - If `Comp` is a component type that is currently *not* assigned to this entity,
/// a new instance of `Comp` will be default initialized and `newValue` will be set at the given keyPath.
///
/// - Parameters:
/// - newValue: The value to set.
/// - componentKeyPath: The `ReferenceWritableKeyPath` to the property of the given component.
/// - Returns: Returns true if an action was performed, false otherwise.
@inlinable
@discardableResult
public func set<Comp, Value>(value newValue: Value?, for componentKeyPath: ReferenceWritableKeyPath<Comp, Value?>) -> Bool where Comp: Component & DefaultInitializable {
guard has(Comp.self) else {
let newInstance = Comp()
newInstance[keyPath: componentKeyPath] = newValue
return nexus.assign(component: newInstance, entityId: identifier)
}
get(component: Comp.self)![keyPath: componentKeyPath] = newValue
return true
}
/// Set the value of a component using the key path to the property in the component.
///
/// **Behavior:**
/// - If `Comp` is a component type that is currently *not* assigned to this entity,
/// a new instance of `Comp` will be default initialized and `newValue` will be set at the given keyPath.
@inlinable
public subscript<Comp, Value>(_ componentKeyPath: ReferenceWritableKeyPath<Comp, Value>) -> Value where Comp: Component & DefaultInitializable {
get { self.get(valueAt: componentKeyPath) }
nonmutating set { self.set(value: newValue, for: componentKeyPath) }
}
/// Set the value of a component using the key path to the property in the component.
///
/// **Behavior:**
/// - If `Comp` is a component type that is currently *not* assigned to this entity,
/// a new instance of `Comp` will be default initialized and `newValue` will be set at the given keyPath.
@inlinable
public subscript<Comp, Value>(_ componentKeyPath: ReferenceWritableKeyPath<Comp, Value?>) -> Value? where Comp: Component & DefaultInitializable {
get { self.get(valueAt: componentKeyPath) }
nonmutating set { self.set(value: newValue, for: componentKeyPath) }
} }
} }

View File

@ -27,6 +27,21 @@ public struct Entity {
nexus.count(components: identifier) nexus.count(components: identifier)
} }
@discardableResult
public func createEntity() -> Entity {
nexus.createEntity()
}
@discardableResult
public func createEntity(with components: Component...) -> Entity {
createEntity(with: components)
}
@discardableResult
public func createEntity<C>(with components: C) -> Entity where C: Collection, C.Element == Component {
nexus.createEntity(with: components)
}
/// Checks if a component with given type is assigned to this entity. /// Checks if a component with given type is assigned to this entity.
/// - Parameter type: the component type. /// - Parameter type: the component type.
public func has<C>(_ type: C.Type) -> Bool where C: Component { public func has<C>(_ type: C.Type) -> Bool where C: Component {
@ -48,9 +63,7 @@ public struct Entity {
/// - Parameter components: one or more components. /// - Parameter components: one or more components.
@discardableResult @discardableResult
public func assign(_ components: Component...) -> Entity { public func assign(_ components: Component...) -> Entity {
for component: Component in components { assign(components)
assign(component)
}
return self return self
} }
@ -66,7 +79,13 @@ public struct Entity {
/// - Parameter component: the typed component. /// - Parameter component: the typed component.
@discardableResult @discardableResult
public func assign<C>(_ component: C) -> Entity where C: Component { public func assign<C>(_ component: C) -> Entity where C: Component {
nexus.assign(component: component, to: self) assign(component)
return self
}
@discardableResult
public func assign<C>(_ components: C) -> Entity where C: Collection, C.Element == Component {
nexus.assign(components: components, to: self)
return self return self
} }
@ -107,32 +126,26 @@ public struct Entity {
public func makeComponentsIterator() -> ComponentsIterator { public func makeComponentsIterator() -> ComponentsIterator {
ComponentsIterator(nexus: nexus, entityIdentifier: identifier) ComponentsIterator(nexus: nexus, entityIdentifier: identifier)
} }
/// Returns a sequence of all componenents of this entity.
@inlinable
public func allComponents() -> AnySequence<Component> {
AnySequence { self.makeComponentsIterator() }
}
} }
extension Entity { extension Entity {
public struct ComponentsIterator: IteratorProtocol { public struct ComponentsIterator: IteratorProtocol {
private var iterator: AnyIterator<Component> private var iterator: IndexingIterator<([Component])>?
@usableFromInline @usableFromInline
init(nexus: Nexus, entityIdentifier: EntityIdentifier) { init(nexus: Nexus, entityIdentifier: EntityIdentifier) {
if let comps = nexus.get(components: entityIdentifier) { iterator = nexus.get(components: entityIdentifier)?
iterator = AnyIterator<Component>(comps.compactMap { nexus.get(component: $0, for: entityIdentifier) }.makeIterator()) .map { nexus.get(unsafe: $0, for: entityIdentifier) }
} else { .makeIterator()
iterator = AnyIterator { nil }
}
} }
public mutating func next() -> Component? { public mutating func next() -> Component? {
iterator.next() iterator?.next()
} }
} }
} }
extension Entity.ComponentsIterator: LazySequenceProtocol { }
extension Entity.ComponentsIterator: Sequence { }
extension Entity: Equatable { extension Entity: Equatable {
public static func == (lhs: Entity, rhs: Entity) -> Bool { public static func == (lhs: Entity, rhs: Entity) -> Bool {

View File

@ -94,6 +94,7 @@ extension Family {
} }
extension Family.ComponentsIterator: LazySequenceProtocol { } extension Family.ComponentsIterator: LazySequenceProtocol { }
extension Family.ComponentsIterator: Sequence { }
// MARK: - entity iterator // MARK: - entity iterator
extension Family { extension Family {
@ -120,6 +121,7 @@ extension Family {
} }
extension Family.EntityIterator: LazySequenceProtocol { } extension Family.EntityIterator: LazySequenceProtocol { }
extension Family.EntityIterator: Sequence { }
// MARK: - entity component iterator // MARK: - entity component iterator
extension Family { extension Family {
@ -146,6 +148,7 @@ extension Family {
} }
extension Family.EntityComponentIterator: LazySequenceProtocol { } extension Family.EntityComponentIterator: LazySequenceProtocol { }
extension Family.EntityComponentIterator: Sequence { }
// MARK: - member creation // MARK: - member creation
extension Family { extension Family {

View File

@ -23,13 +23,13 @@ public struct Requires1<Comp1>: FamilyRequirementsManaging where Comp1: Componen
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
return (comp1) return (comp1)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
return (entity, comp1) return (entity, comp1)
} }
@ -116,15 +116,15 @@ public struct Requires2<Comp1, Comp2>: FamilyRequirementsManaging where Comp1: C
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
return (comp1, comp2) return (comp1, comp2)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2) return (entity, comp1, comp2)
} }
@ -215,17 +215,17 @@ public struct Requires3<Comp1, Comp2, Comp3>: FamilyRequirementsManaging where C
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
return (comp1, comp2, comp3) return (comp1, comp2, comp3)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2, comp3) return (entity, comp1, comp2, comp3)
} }
@ -320,19 +320,19 @@ public struct Requires4<Comp1, Comp2, Comp3, Comp4>: FamilyRequirementsManaging
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
return (comp1, comp2, comp3, comp4) return (comp1, comp2, comp3, comp4)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2, comp3, comp4) return (entity, comp1, comp2, comp3, comp4)
} }
@ -431,21 +431,21 @@ public struct Requires5<Comp1, Comp2, Comp3, Comp4, Comp5>: FamilyRequirementsMa
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
return (comp1, comp2, comp3, comp4, comp5) return (comp1, comp2, comp3, comp4, comp5)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2, comp3, comp4, comp5) return (entity, comp1, comp2, comp3, comp4, comp5)
} }
@ -548,23 +548,23 @@ public struct Requires6<Comp1, Comp2, Comp3, Comp4, Comp5, Comp6>: FamilyRequire
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5, Comp6) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5, Comp6) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
let comp6: Comp6 = nexus.get(unsafeComponentFor: entityId) let comp6: Comp6 = nexus.get(unsafe: entityId)
return (comp1, comp2, comp3, comp4, comp5, comp6) return (comp1, comp2, comp3, comp4, comp5, comp6)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5, Comp6) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5, Comp6) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
let comp6: Comp6 = nexus.get(unsafeComponentFor: entityId) let comp6: Comp6 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2, comp3, comp4, comp5, comp6) return (entity, comp1, comp2, comp3, comp4, comp5, comp6)
} }
@ -671,25 +671,25 @@ public struct Requires7<Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7>: Family
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
let comp6: Comp6 = nexus.get(unsafeComponentFor: entityId) let comp6: Comp6 = nexus.get(unsafe: entityId)
let comp7: Comp7 = nexus.get(unsafeComponentFor: entityId) let comp7: Comp7 = nexus.get(unsafe: entityId)
return (comp1, comp2, comp3, comp4, comp5, comp6, comp7) return (comp1, comp2, comp3, comp4, comp5, comp6, comp7)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
let comp6: Comp6 = nexus.get(unsafeComponentFor: entityId) let comp6: Comp6 = nexus.get(unsafe: entityId)
let comp7: Comp7 = nexus.get(unsafeComponentFor: entityId) let comp7: Comp7 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2, comp3, comp4, comp5, comp6, comp7) return (entity, comp1, comp2, comp3, comp4, comp5, comp6, comp7)
} }
@ -800,27 +800,27 @@ public struct Requires8<Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7, Comp8>:
} }
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7, Comp8) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> (Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7, Comp8) {
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
let comp6: Comp6 = nexus.get(unsafeComponentFor: entityId) let comp6: Comp6 = nexus.get(unsafe: entityId)
let comp7: Comp7 = nexus.get(unsafeComponentFor: entityId) let comp7: Comp7 = nexus.get(unsafe: entityId)
let comp8: Comp8 = nexus.get(unsafeComponentFor: entityId) let comp8: Comp8 = nexus.get(unsafe: entityId)
return (comp1, comp2, comp3, comp4, comp5, comp6, comp7, comp8) return (comp1, comp2, comp3, comp4, comp5, comp6, comp7, comp8)
} }
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7, Comp8) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, Comp1, Comp2, Comp3, Comp4, Comp5, Comp6, Comp7, Comp8) {
let entity = Entity(nexus: nexus, id: entityId) let entity = Entity(nexus: nexus, id: entityId)
let comp1: Comp1 = nexus.get(unsafeComponentFor: entityId) let comp1: Comp1 = nexus.get(unsafe: entityId)
let comp2: Comp2 = nexus.get(unsafeComponentFor: entityId) let comp2: Comp2 = nexus.get(unsafe: entityId)
let comp3: Comp3 = nexus.get(unsafeComponentFor: entityId) let comp3: Comp3 = nexus.get(unsafe: entityId)
let comp4: Comp4 = nexus.get(unsafeComponentFor: entityId) let comp4: Comp4 = nexus.get(unsafe: entityId)
let comp5: Comp5 = nexus.get(unsafeComponentFor: entityId) let comp5: Comp5 = nexus.get(unsafe: entityId)
let comp6: Comp6 = nexus.get(unsafeComponentFor: entityId) let comp6: Comp6 = nexus.get(unsafe: entityId)
let comp7: Comp7 = nexus.get(unsafeComponentFor: entityId) let comp7: Comp7 = nexus.get(unsafe: entityId)
let comp8: Comp8 = nexus.get(unsafeComponentFor: entityId) let comp8: Comp8 = nexus.get(unsafe: entityId)
return (entity, comp1, comp2, comp3, comp4, comp5, comp6, comp7, comp8) return (entity, comp1, comp2, comp3, comp4, comp5, comp6, comp7, comp8)
} }

View File

@ -21,39 +21,50 @@ extension Nexus {
componentIdsByEntity[entityId]?.count ?? 0 componentIdsByEntity[entityId]?.count ?? 0
} }
public final func assign(component: Component, to entity: Entity) { @discardableResult
public final func assign(component: Component, to entity: Entity) -> Bool {
let entityId: EntityIdentifier = entity.identifier let entityId: EntityIdentifier = entity.identifier
assign(component: component, entityId: entityId) defer { delegate?.nexusEvent(ComponentAdded(component: component.identifier, toEntity: entity.identifier)) }
delegate?.nexusEvent(ComponentAdded(component: component.identifier, toEntity: entity.identifier)) return assign(component: component, entityId: entityId)
} }
public final func assign<C>(component: C, to entity: Entity) where C: Component { @discardableResult
public final func assign<C>(component: C, to entity: Entity) -> Bool where C: Component {
assign(component: component, to: entity) assign(component: component, to: entity)
} }
@discardableResult
public final func assign<C>(components: C, to entity: Entity) -> Bool where C: Collection, C.Element == Component {
assign(components: components, to: entity.identifier)
}
@inlinable @inlinable
public final func get(component componentId: ComponentIdentifier, for entityId: EntityIdentifier) -> Component? { public final func get(safe componentId: ComponentIdentifier, for entityId: EntityIdentifier) -> Component? {
guard let uniformComponents = componentsByType[componentId] else { guard let uniformComponents = componentsByType[componentId], uniformComponents.contains(entityId.index) else {
return nil return nil
} }
return uniformComponents.get(at: entityId.index) return uniformComponents.get(at: entityId.index)
} }
@inlinable @inlinable
public final func get(unsafeComponent componentId: ComponentIdentifier, for entityId: EntityIdentifier) -> Component { public final func get(unsafe componentId: ComponentIdentifier, for entityId: EntityIdentifier) -> Component {
let uniformComponents = componentsByType[componentId].unsafelyUnwrapped let uniformComponents = componentsByType[componentId].unsafelyUnwrapped
return uniformComponents.get(unsafeAt: entityId.index) return uniformComponents.get(unsafeAt: entityId.index)
} }
@inlinable @inlinable
public final func get<C>(for entityId: EntityIdentifier) -> C? where C: Component { public final func get<C>(safe componentId: ComponentIdentifier, for entityId: EntityIdentifier) -> C? where C: Component {
let componentId: ComponentIdentifier = C.identifier get(safe: componentId, for: entityId) as? C
return get(componentId: componentId, entityId: entityId)
} }
@inlinable @inlinable
public final func get<C>(unsafeComponentFor entityId: EntityIdentifier) -> C where C: Component { public final func get<C>(safe entityId: EntityIdentifier) -> C? where C: Component {
let component: Component = get(unsafeComponent: C.identifier, for: entityId) get(safe: C.identifier, for: entityId)
}
@inlinable
public final func get<C>(unsafe entityId: EntityIdentifier) -> C where C: Component {
let component: Component = get(unsafe: C.identifier, for: entityId)
// components are guaranteed to be reference types so unsafeDowncast is applicable here // components are guaranteed to be reference types so unsafeDowncast is applicable here
return unsafeDowncast(component, to: C.self) return unsafeDowncast(component, to: C.self)
} }
@ -89,12 +100,4 @@ extension Nexus {
} }
return removedAll return removedAll
} }
@inlinable
public final func get<C>(componentId: ComponentIdentifier, entityId: EntityIdentifier) -> C? where C: Component {
guard let uniformComponents = componentsByType[componentId] else {
return nil
}
return uniformComponents.get(at: entityId.index) as? C
}
} }

View File

@ -33,6 +33,13 @@ extension Nexus {
componentIdsByEntity.keys.count componentIdsByEntity.keys.count
} }
/// Creates an iterator over all entities in the nexus.
///
/// Entity order is not guaranteed to stay the same over iterations.
public func makeEntitiesIterator() -> EntitiesIterator {
EntitiesIterator(nexus: self)
}
public func exists(entity entityId: EntityIdentifier) -> Bool { public func exists(entity entityId: EntityIdentifier) -> Bool {
componentIdsByEntity.keys.contains(entityId) componentIdsByEntity.keys.contains(entityId)
} }
@ -67,3 +74,27 @@ extension Nexus {
return true return true
} }
} }
// MARK: - entities iterator
extension Nexus {
public struct EntitiesIterator: IteratorProtocol {
private var iterator: AnyIterator<Entity>
@usableFromInline
init(nexus: Nexus) {
var iter = nexus.componentIdsByEntity.keys.makeIterator()
iterator = AnyIterator {
guard let entityId = iter.next() else {
return nil
}
return Entity(nexus: nexus, id: entityId)
}
}
public func next() -> Entity? {
iterator.next()
}
}
}
extension Nexus.EntitiesIterator: LazySequenceProtocol { }
extension Nexus.EntitiesIterator: Sequence { }

View File

@ -6,7 +6,9 @@
// //
extension Nexus { extension Nexus {
func assign<C>(components: C, to entityId: EntityIdentifier) where C: Collection, C.Element == Component { @usableFromInline
@discardableResult
func assign<C>(components: C, to entityId: EntityIdentifier) -> Bool where C: Collection, C.Element == Component {
var iter = components.makeIterator() var iter = components.makeIterator()
while let component = iter.next() { while let component = iter.next() {
let componentId = component.identifier let componentId = component.identifier
@ -14,7 +16,7 @@ extension Nexus {
guard !has(componentId: componentId, entityId: entityId) else { guard !has(componentId: componentId, entityId: entityId) else {
delegate?.nexusNonFatalError("ComponentAdd collision: \(entityId) already has a component \(component)") delegate?.nexusNonFatalError("ComponentAdd collision: \(entityId) already has a component \(component)")
assertionFailure("ComponentAdd collision: \(entityId) already has a component \(component)") assertionFailure("ComponentAdd collision: \(entityId) already has a component \(component)")
return return false
} }
// add component instances to uniform component stores // add component instances to uniform component stores
@ -26,16 +28,18 @@ extension Nexus {
// Update entity membership // Update entity membership
update(familyMembership: entityId) update(familyMembership: entityId)
return true
} }
func assign(component: Component, entityId: EntityIdentifier) { @usableFromInline
func assign(component: Component, entityId: EntityIdentifier) -> Bool {
let componentId = component.identifier let componentId = component.identifier
// test if component is already assigned // test if component is already assigned
guard !has(componentId: componentId, entityId: entityId) else { guard !has(componentId: componentId, entityId: entityId) else {
delegate?.nexusNonFatalError("ComponentAdd collision: \(entityId) already has a component \(component)") delegate?.nexusNonFatalError("ComponentAdd collision: \(entityId) already has a component \(component)")
assertionFailure("ComponentAdd collision: \(entityId) already has a component \(component)") assertionFailure("ComponentAdd collision: \(entityId) already has a component \(component)")
return return false
} }
// add component instances to uniform component stores // add component instances to uniform component stores
@ -46,8 +50,10 @@ extension Nexus {
// Update entity membership // Update entity membership
update(familyMembership: entityId) update(familyMembership: entityId)
return true
} }
@usableFromInline
func insertComponentInstance(_ component: Component, _ componentId: ComponentIdentifier, _ entityId: EntityIdentifier) { func insertComponentInstance(_ component: Component, _ componentId: ComponentIdentifier, _ entityId: EntityIdentifier) {
if componentsByType[componentId] == nil { if componentsByType[componentId] == nil {
componentsByType[componentId] = ManagedContiguousArray<Component>() componentsByType[componentId] = ManagedContiguousArray<Component>()
@ -55,10 +61,12 @@ extension Nexus {
componentsByType[componentId]?.insert(component, at: entityId.index) componentsByType[componentId]?.insert(component, at: entityId.index)
} }
@usableFromInline
func assign(_ componentId: ComponentIdentifier, _ entityId: EntityIdentifier) { func assign(_ componentId: ComponentIdentifier, _ entityId: EntityIdentifier) {
componentIdsByEntity[entityId]!.insert(componentId) componentIdsByEntity[entityId]!.insert(componentId)
} }
@usableFromInline
func update(familyMembership entityId: EntityIdentifier) { func update(familyMembership entityId: EntityIdentifier) {
// FIXME: iterating all families is costly for many families // FIXME: iterating all families is costly for many families
// FIXME: this could be parallelized // FIXME: this could be parallelized

View File

@ -28,7 +28,7 @@ extension Single where A: SingleComponent {
// Since we guarantee that the component will always be present by managing the complete lifecycle of the entity // Since we guarantee that the component will always be present by managing the complete lifecycle of the entity
// and component assignment we may unsafelyUnwrap here. // and component assignment we may unsafelyUnwrap here.
// Since components will always be of reference type (class) we may use unsafeDowncast here for performance reasons. // Since components will always be of reference type (class) we may use unsafeDowncast here for performance reasons.
nexus.get(unsafeComponentFor: entityId) nexus.get(unsafe: entityId)
} }
public var entity: Entity { public var entity: Entity {

View File

@ -46,7 +46,7 @@ public struct Requires{{ idx }}<{{ CompParams }}>: FamilyRequirementsManaging wh
public static func components(nexus: Nexus, entityId: EntityIdentifier) -> ({{ CompParams }}) { public static func components(nexus: Nexus, entityId: EntityIdentifier) -> ({{ CompParams }}) {
{% for comp in components %} {% for comp in components %}
let {{ comp|lowercase }}: {{ comp }} = nexus.get(unsafeComponentFor: entityId) let {{ comp|lowercase }}: {{ comp }} = nexus.get(unsafe: entityId)
{% endfor %} {% endfor %}
return ({{ CompsLowercased }}) return ({{ CompsLowercased }})
} }
@ -54,7 +54,7 @@ public struct Requires{{ idx }}<{{ CompParams }}>: FamilyRequirementsManaging wh
public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, {{ CompParams }}) { public static func entityAndComponents(nexus: Nexus, entityId: EntityIdentifier) -> (Entity, {{ CompParams }}) {
let entity: Entity = Entity(nexus: nexus, id: entityId) let entity: Entity = Entity(nexus: nexus, id: entityId)
{% for comp in components %} {% for comp in components %}
let {{ comp|lowercase }}: {{ comp }} = nexus.get(unsafeComponentFor: entityId) let {{ comp|lowercase }}: {{ comp }} = nexus.get(unsafe: entityId)
{% endfor %} {% endfor %}
return (entity, {{ CompsLowercased }}) return (entity, {{ CompsLowercased }})
} }

View File

@ -226,6 +226,8 @@ extension UnorderedSparseSet: Sequence {
} }
} }
} }
extension UnorderedSparseSet.ElementIterator: LazySequenceProtocol { }
extension UnorderedSparseSet.ElementIterator: Sequence { }
// MARK: - Equatable // MARK: - Equatable
extension UnorderedSparseSet.Storage.Entry: Equatable where Element: Equatable { } extension UnorderedSparseSet.Storage.Entry: Equatable where Element: Equatable { }

View File

@ -10,17 +10,48 @@ import FirebladeECS
class EmptyComponent: Component { class EmptyComponent: Component {
} }
class Name: Component { final class Optionals: Component, DefaultInitializable {
var int: Int?
var float: Float?
var string: String?
convenience init() {
self.init(nil, nil, nil)
}
init(_ int: Int?, _ float: Float?, _ string: String?) {
self.int = int
self.float = float
self.string = string
}
}
extension Optionals: Equatable {
static func == (lhs: Optionals, rhs: Optionals) -> Bool {
lhs.int == rhs.int &&
lhs.float == rhs.float &&
lhs.string == rhs.string
}
}
final class Name: Component, DefaultInitializable {
var name: String var name: String
init(name: String) { init(name: String) {
self.name = name self.name = name
} }
convenience init() {
self.init(name: "")
}
} }
final class Position: Component { final class Position: Component, DefaultInitializable {
var x: Int var x: Int
var y: Int var y: Int
convenience init() {
self.init(x: 0, y: 0)
}
init(x: Int, y: Int) { init(x: Int, y: Int) {
self.x = x self.x = x
self.y = y self.y = y
@ -28,11 +59,16 @@ final class Position: Component {
} }
extension Position: Codable { } extension Position: Codable { }
class Velocity: Component { final class Velocity: Component, DefaultInitializable {
var a: Float var a: Float
init(a: Float) { init(a: Float) {
self.a = a self.a = a
} }
convenience init() {
self.init(a: 0)
}
} }
final class Party: Component { final class Party: Component {

View File

@ -34,7 +34,7 @@ class EntityTests: XCTestCase {
entity.assign(name, vel) entity.assign(name, vel)
let expectedComponents: [Component] = [pos, name, vel] let expectedComponents: [Component] = [pos, name, vel]
let allComponents = entity.allComponents() let allComponents = Array(entity.makeComponentsIterator())
XCTAssertTrue(allComponents.elementsEqualUnordered(expectedComponents) { $0 === $1 }) XCTAssertTrue(allComponents.elementsEqualUnordered(expectedComponents) { $0 === $1 })
} }
@ -101,11 +101,72 @@ class EntityTests: XCTestCase {
XCTAssertEqual(entity[\Name.name], "AnotherName") XCTAssertEqual(entity[\Name.name], "AnotherName")
entity[\Velocity.a] = 123 entity[\Velocity.a] = 123
XCTAssertNil(entity[\Velocity.a]) XCTAssertEqual(entity[\Velocity.a], 123.0)
entity[Position.self]?.x = 1234 entity[Position.self]?.x = 1234
XCTAssertEqual(entity[Position.self]?.x, 1234) XCTAssertEqual(entity[Position.self]?.x, 1234)
XCTAssertNil(entity[Velocity.self]?.a) XCTAssertEqual(entity[Velocity.self]?.a, 123.0)
// remove position component
entity[Position.self] = nil
XCTAssertNil(entity[Position.self])
entity[Position.self] = pos // assign position comp instance
XCTAssertTrue(entity[Position.self] === pos)
entity[Position.self] = pos // re-assign
XCTAssertTrue(entity[Position.self] === pos)
entity[Position.self] = nil // remove position component
XCTAssertNil(entity[Position.self])
let opts = Optionals(1, 2, "hello")
entity[Optionals.self] = opts
XCTAssertEqual(entity[Optionals.self], opts)
entity[\Optionals.float] = nil
XCTAssertEqual(entity[\Optionals.float], nil)
XCTAssertEqual(entity[\Optionals.int], 1)
XCTAssertEqual(entity[\Optionals.string], "hello")
entity[Optionals.self] = nil
XCTAssertNil(entity[Optionals.self])
entity[\Optionals.string] = "world"
XCTAssertEqual(entity[\Optionals.string], "world")
entity.assign(Comp1(12))
XCTAssertEqual(entity[\Comp1.value], 12)
}
func testComponentsIteration() {
let nexus = Nexus()
let entity = nexus.createEntity()
XCTAssertTrue(Array(entity.makeComponentsIterator()).isEmpty)
entity.assign(Position())
XCTAssertEqual(Array(entity.makeComponentsIterator()).count, 1)
}
func testEntityCreationIntrinsic() {
let nexus = Nexus()
let entity = nexus.createEntity()
let secondEntity = entity.createEntity()
XCTAssertNotEqual(secondEntity, entity)
let thirdEntity = secondEntity.createEntity()
XCTAssertNotEqual(secondEntity, thirdEntity)
XCTAssertNotEqual(entity, thirdEntity)
let entityWithComponents = entity.createEntity(with: Position(), Name())
XCTAssertTrue(entityWithComponents.has(Position.self))
XCTAssertTrue(entityWithComponents.has(Name.self))
XCTAssertEqual(nexus.numEntities, 4)
XCTAssertEqual(nexus.numComponents, 2)
}
func testEntityDescriptions() {
let nexus = Nexus()
let entt = nexus.createEntity()
XCTAssertFalse(entt.description.isEmpty)
XCTAssertFalse(entt.debugDescription.isEmpty)
} }
} }

View File

@ -155,4 +155,15 @@ class NexusTests: XCTestCase {
XCTAssert(pB.x != pA.x) XCTAssert(pB.x != pA.x)
XCTAssert(pB.y != pA.y) XCTAssert(pB.y != pA.y)
} }
func testEntityIteration() {
nexus.createEntities(count: 1000) { ctx in Position(x: ctx.index, y: ctx.index) }
let entityArray = [Entity](nexus.makeEntitiesIterator()).lazy
XCTAssertEqual(entityArray.count, 1000)
XCTAssertTrue(entityArray.contains(where: { $0.identifier.index == 0 }))
XCTAssertTrue(entityArray.contains(where: { $0.identifier.index == 999 }))
}
} }

View File

@ -140,6 +140,9 @@ extension EntityTests {
// to regenerate. // to regenerate.
static let __allTests__EntityTests = [ static let __allTests__EntityTests = [
("testAllComponentsOfEntity", testAllComponentsOfEntity), ("testAllComponentsOfEntity", testAllComponentsOfEntity),
("testComponentsIteration", testComponentsIteration),
("testEntityCreationIntrinsic", testEntityCreationIntrinsic),
("testEntityDescriptions", testEntityDescriptions),
("testEntityEquality", testEntityEquality), ("testEntityEquality", testEntityEquality),
("testEntityIdentifierAndIndex", testEntityIdentifierAndIndex), ("testEntityIdentifierAndIndex", testEntityIdentifierAndIndex),
("testEntityIdGenerator", testEntityIdGenerator), ("testEntityIdGenerator", testEntityIdGenerator),
@ -342,7 +345,8 @@ extension NexusTests {
("testComponentRetrieval", testComponentRetrieval), ("testComponentRetrieval", testComponentRetrieval),
("testComponentUniqueness", testComponentUniqueness), ("testComponentUniqueness", testComponentUniqueness),
("testEntityCreate", testEntityCreate), ("testEntityCreate", testEntityCreate),
("testEntityDestroy", testEntityDestroy) ("testEntityDestroy", testEntityDestroy),
("testEntityIteration", testEntityIteration)
] ]
} }