sourcelib/Ecs.xtl

1⍝│ Ecs: an entity-component system as arrays, shared by the games built 2⍝│ on it. A world is one matrix of numbers: a row per entity slot, and 3⍝│ columns for its fields. Column 1 says whether the slot holds a living 4⍝│ entity (1) or is free (0); each component then takes a column saying 5⍝│ whether the entity has it, followed by its fields. Entities are row 6⍝│ numbers. A system is a whole-column expression: every entity with 7⍝│ the components it needs, at once. The macro library Ecs.xtlm, under 8⍝│ the same alias, writes a world's layout from a list of components 9⍝│ (getters, setters, masks); these are the functions any world uses. 10 11⍝━━ Living entities 12 13⍝ :: (Num a, Truthy b) => a -> b 14⍝│ Which slots hold a living entity: column 1. 15⍝│ >> "ec:" u_se< "Ecs" 16⍝│ >> ec:a_live 3 2 r_eshape 1.0 7 0.0 0 1.0 9 17⍝│ 1 0 1 18ˡa̲live ← { W → 0 < 1 s̲elect₂ W } 19⍝ :: (Num a, Num b, Truthy b) => a -> b 20⍝│ How many entities are alive. 21ˡc̲ount ← { W → '+ r̲/ 0 + ˡa̲live W } 22⍝ :: Float -> (Int, Int, Float) -> Float 23⍝│ The world W with values written at rows ids and columns cols (vals: a 24⍝│ number for all, or a value per row, or a row of values per row), every 25⍝│ cell at once: the rows and the columns as one-hot tables, the cells 26⍝│ outside left as they were. 27⍝│ >> "ec:" u_se< "Ecs" 28⍝│ >> W := 3 3 r_eshape 0.0 29⍝│ >> W ec:p_ut (2 3, 3, 5.0 6.0) 30⍝│ 0.0 0.0 0.0 31⍝│ 0.0 0.0 0.0 32⍝│ 0.0 5.0 6.0 33ˡp̲ut ← { W (cols, ids, vals) → 34 c ← r̲avel cols 35 i ← r̲avel ids 36 R ← f̲loat (r̲ange t̲ally W) '= t̲able i 37 K ← f̲loat c '= t̲able r̲ange 2 s̲elect s̲hape W 38 V ← ((t̲ally i) c̲at t̲ally c) r̲eshape vals 39 M ← 0 < R '+ '× i̲nner (((t̲ally i) c̲at t̲ally c) r̲eshape 1.0) '+ '× i̲nner K 40 (W × f̲loat n̲ot M) + R '+ '× i̲nner V '+ '× i̲nner K 41} 42 43⍝━━ Spawning and despawning 44 45⍝ :: Float -> Int -> (Float, Int) 46⍝│ Room for n new entities: the world with the first n free slots made 47⍝│ alive, and their numbers (fewer when the world is nearly full). 48⍝│ >> "ec:" u_se< "Ecs" 49⍝│ >> (W, ids) := (4 3 r_eshape 0.0) ec:s_pawn 2 50⍝│ >> ids 51⍝│ 1 2 52ˡs̲pawn ← { W n → 53 ids ← n t̲ake w̲here n̲ot ˡa̲live W 54 (W ˡp̲ut (1, ids, 1.0), ids) 55} 56⍝ :: Float -> Int -> Float 57⍝│ The world with entities ids gone: their rows cleared, every column. 58ˡd̲espawn ← { W ids → W × f̲loat (n̲ot (r̲ange t̲ally W) m̲ember? r̲avel ids) '× t̲able (2 s̲elect s̲hape W) r̲eshape 1 } 59 60⍝━━ Systems' helpers 61 62⍝ :: (Num a, Truthy b) => (a, a, a) -> b 63⍝│ Which points of P are within distance d of which points of Q (both 64⍝│ n by 2, x then y): a table of every pair at once, P's rows down. 65⍝│ >> "ec:" u_se< "Ecs" 66⍝│ >> ec:n_ear (2 2 r_eshape 0 0 5 5.0, 1 2 r_eshape 1 0.0, 1.5) 67⍝│ 1 68⍝│ 0 69ˡn̲ear ← { (P, Q, d) → 70 dx ← (1 s̲elect₂ P) '− t̲able 1 s̲elect₂ Q 71 dy ← (2 s̲elect₂ P) '− t̲able 2 s̲elect₂ Q 72 ((dx × dx) + dy × dy) ≤ d × d 73}