1+ import { Entity } from "./entity" ;
2+ import { Macro } from "./macro" ;
3+
4+ class EntityNotValidError extends Error { }
5+ class EntityRepeatRegisteredError extends Error { }
6+ class EntityGroupOutOfRangeYouCanOpenAutoResize extends Error { }
7+ class DomainDefinition {
8+ private _entities : ( Entity | null ) [ ]
9+ private _entityVersion : number [ ]
10+ private _destroyEntityId : number [ ]
11+ private _entityIdCursor = 0 ;
12+
13+ constructor ( public capacity = 50 , public autoResize = true ) {
14+ this . _entities = new Array < Entity > ( capacity ) ;
15+ this . _entityVersion = new Array < number > ( capacity ) ;
16+ this . _entityVersion . fill ( 0 ) ;
17+ this . _destroyEntityId = new Array < number > ( capacity ) ;
18+ }
19+
20+ reg ( entity : Entity ) {
21+ if ( this . isValid ( entity ) )
22+ throw new EntityRepeatRegisteredError ( entity . toString ( ) ) ;
23+ if ( this . _entityIdCursor == this . capacity && this . autoResize )
24+ this . resize ( Math . ceil ( this . capacity * 1.5 ) )
25+ else
26+ throw new EntityGroupOutOfRangeYouCanOpenAutoResize (
27+ `Domain: capacity: ${ this . capacity } ; ` + entity . toString ( ) ) ;
28+ this . _unlockEntity ( entity ) ;
29+ entity . id = this . _getEntityId ( ) ;
30+ entity . version = this . _entityVersion [ entity . id ] ;
31+ this . _lockEntity ( entity ) ;
32+ this . _entities [ entity . id ] = entity ;
33+ }
34+
35+ unreg ( entity : Entity ) {
36+ if ( ! this . isValid ( entity ) )
37+ throw new EntityNotValidError ( entity . toString ( ) ) ;
38+ this . _entityVersion [ entity . id ] ++ ;
39+ this . _destroyEntityId . push ( entity . id ) ;
40+ this . _entities [ entity . id ] = null ;
41+ }
42+
43+ resize ( newSize : number ) {
44+ const oldSize = this . capacity ;
45+ this . _entities . length = newSize ;
46+ this . _entityVersion . length = newSize ;
47+ this . _entityVersion . fill ( 0 , oldSize , newSize ) ;
48+ this . capacity = newSize ;
49+ }
50+
51+ isValid ( entity : Entity ) {
52+ return entity . id != Macro . NULL_NUM
53+ && entity . version != Macro . NULL_NUM
54+ && entity . version == this . _entityVersion [ entity . id ]
55+ }
56+
57+ private _getEntityId ( ) {
58+ return this . _destroyEntityId . length > 0
59+ ? this . _destroyEntityId . unshift ( )
60+ : this . _entityIdCursor ++ ;
61+ }
62+
63+ private _lockEntity ( entity : Entity ) {
64+ Object . defineProperties ( entity , {
65+ "id" : { writable : false } ,
66+ "version" : { writable : false }
67+ } )
68+ }
69+
70+ private _unlockEntity ( entity : Entity ) {
71+ Object . defineProperties ( entity , {
72+ "id" : { writable : true } ,
73+ "version" : { writable : true }
74+ } )
75+ }
76+ }
77+
78+ export const Domain = new DomainDefinition ( ) ;
0 commit comments