librarylib/Ecs.xtl

Ecs: an entity-component system as arrays, shared by the games built on it. A world is one matrix of numbers: a row per entity slot, and columns for its fields. Column 1 says whether the slot holds a living entity (1) or is free (0); each component then takes a column saying whether the entity has it, followed by its fields. Entities are row numbers. A system is a whole-column expression: every entity with the components it needs, at once. The macro library Ecs.xtlm, under the same alias, writes a world's layout from a list of components (getters, setters, masks); these are the functions any world uses.

source

Living entities

ˡa̲live : (Num a, Truthy b) => a -> b

function · line 18

Which slots hold a living entity: column 1.

      "ec:" u̲se< "Ecs"
      ᵉᶜa̲live 3 2 r̲eshape 1.0 7 0.0 0 1.0 9
1 0 1
ˡa̲live ← { W → 0 < 1 s̲elect₂ W }

ˡc̲ount : (Num a, Num b, Truthy b) => a -> b

function · line 21

How many entities are alive.

ˡc̲ount ← { W → '+ r̲/ 0 + ˡa̲live W }

ˡp̲ut : Float -> (Int, Int, Float) -> Float

function · line 33

The world W with values written at rows ids and columns cols (vals: a number for all, or a value per row, or a row of values per row), every cell at once: the rows and the columns as one-hot tables, the cells outside left as they were.

      "ec:" u̲se< "Ecs"
      W ← 3 3 r̲eshape 0.0
      W ᵉᶜp̲ut (2 3, 3, 5.0 6.0)
0.0 0.0 0.0
0.0 0.0 0.0
0.0 5.0 6.0
ˡp̲ut ← { W (cols, ids, vals) →
  c ← r̲avel cols
  i ← r̲avel ids
  R ← f̲loat (r̲ange t̲ally W) '= t̲able i
  K ← f̲loat c '= t̲able r̲ange 2 s̲elect s̲hape W
  V ← ((t̲ally i) c̲at t̲ally c) r̲eshape vals
  M ← 0 < R '+ '× i̲nner (((t̲ally i) c̲at t̲ally c) r̲eshape 1.0) '+ '× i̲nner K
  (W × f̲loat n̲ot M) + R '+ '× i̲nner V '+ '× i̲nner K
}
Used in: ˡs̲pawn

Spawning and despawning

ˡs̲pawn : Float -> Int -> (Float, Int)

function · line 52

Room for n new entities: the world with the first n free slots made alive, and their numbers (fewer when the world is nearly full).

      "ec:" u̲se< "Ecs"
      (W, ids) ← (4 3 r̲eshape 0.0) ᵉᶜs̲pawn 2
      ids
1 2
ˡs̲pawn ← { W n →
  ids ← n t̲ake w̲here n̲ot ˡa̲live W
  (W ˡp̲ut (1, ids, 1.0), ids)
}

ˡd̲espawn : Float -> Int -> Float

function · line 58

The world with entities ids gone: their rows cleared, every column.

ˡ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 }

Systems' helpers

ˡn̲ear : (Num a, Truthy b) => (a, a, a) -> b

function · line 69

Which points of P are within distance d of which points of Q (both n by 2, x then y): a table of every pair at once, P's rows down.

      "ec:" u̲se< "Ecs"
      ᵉᶜn̲ear (2 2 r̲eshape 0 0 5 5.0, 1 2 r̲eshape 1 0.0, 1.5)
1
0
ˡn̲ear ← { (P, Q, d) →
  dx ← (1 s̲elect₂ P) '− t̲able 1 s̲elect₂ Q
  dy ← (2 s̲elect₂ P) '− t̲able 2 s̲elect₂ Q
  ((dx × dx) + dy × dy) ≤ d × d
}