-
Notifications
You must be signed in to change notification settings - Fork 1
/
EntityManager.swift
56 lines (46 loc) · 1.54 KB
/
EntityManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// EntityManager.swift
// star-dash
//
// Created by Lau Rui han on 12/3/24.
//
import Foundation
typealias ComponentSet = Set<ComponentId>
typealias ComponentMap = [ComponentId: Component]
typealias EntityMap = [EntityId: Entity]
typealias EntityComponentMap = [EntityId: ComponentSet]
class EntityManager {
var componentMap: ComponentMap
var entityMap: EntityMap
var entityComponentMap: EntityComponentMap
init(componentMap: ComponentMap, entityMap: EntityMap, entityComponentMap: EntityComponentMap) {
self.componentMap = componentMap
self.entityMap = entityMap
self.entityComponentMap = entityComponentMap
}
convenience init() {
self.init(componentMap: .init(), entityMap: .init(), entityComponentMap: .init())
}
func add(component: Component) {
guard self.componentMap[component.id] != nil else {
return
}
self.componentMap[component.id] = component
self.entityComponentMap[component.entityId]?.insert(component.id)
}
func add(entity: Entity) {
guard self.entityMap[entity.id] != nil else {
return
}
self.entityMap[entity.id] = entity
}
func component<T: Component>(ofType type: T.Type, of entityId: EntityId) -> T? {
guard let components = entityComponentMap[entityId] else {
return nil
}
guard let componentId = components.first(where: { componentMap[$0] is T }) else {
return nil
}
return componentMap[componentId] as? T
}
}