; places actors from a valid actor table
; in the current map's header. This will overwrite the
; header loaded by map_load. Preserves player entry.
+ ; the length of the actor table must be maskable
; inputs:
; a loaded map
; [map_header] ptr
mapgen_place_actors:
+ ; clear everything past player
+ ld hl, p0_units + act_size
+ ld bc, (UNITS_MAX - 1) * act_size
+ ld d, 0
+ call memset
+
; load map ptr
ld a, [map_header]
ld l, a
ld a, [map_header+1]
ld h, a
+ ; now load the actor table template into hl
+ ld de, map_actor_table_ptr
+ add hl, de
+ ; hl = actor table ptr
+
+ ; load actor table ptr
+ ld a, [hl+]
+ ld b, a
+ ld a, [hl+]
+ ; hl = map header actor table ptr
+ ld h, a
+ ld l, b
+
+ ld a, [hl+]
+ ld c, a
+ cp a, 0
+ ret z ; if length is 0 we bail
+ ; c = actor table length
+ ; hl = actor entries
+
+ ; load actor table starting after plater
+ ld de, p0_units + act_size
+ ; de = actor table
+
+ ; b = loop counter
+ ld b, UNITS_MAX - 1
+@spawn_another:
+ push bc
+ push de
+ push hl
+ call rand
+ pop hl
+ pop de
+ pop bc
+
+ ; mask the rand result
+ and a, c
+
+ ; now we know which actor to pick
+ add a, a ; * 2 because the table is a ptr table
+
+ push hl
+ push bc
+ push de
+
+ ld d, 0
+ ld e, a
+ add hl, de
+ ; hl = actor picked ptr
+ ld a, [hl+]
+ ld e, a
+ ld a, [hl+]
+ ld d, a
+ ; de = actor picked = src
+
+
+ pop hl ; hl = actor table dst
+ push hl ; re-push for pop de later
+ ld bc, act_size
+ call memcpy
+
+ pop de
+ pop bc
+ pop hl
+
+ ; move to next actor table entry
+ push hl
+ call mapgent_unit_randomize_or_realod_position
+ ld hl, act_size
+ add hl, de
+ push hl
+ pop de ; de = next entry
+ pop hl
+
+ dec b
+ jp nz, @spawn_another
+
+ ; TODO: reload flags and positions
+
+ ret
+
+ ; randomizes (or reloads from sram)
+ ; an actors position
+ ; inputs:
+ ; de: actor table entry
+ ; preserves all registers
+mapgent_unit_randomize_or_realod_position:
+ ; TODO: check if new position is wall and if so
+ ; try again
+ push_all
+ ld hl, act_pos_y
+ add hl, de ; hl = y pos
+
+ ; select position
+ push hl
+ call rand
+ pop hl
+ and a, MAP_H - 1
+ ld [hl+], a
+
+ push hl
+ call rand
+ pop hl
+ and a, MAP_W - 1
+ ld [hl], a
+
+ pop_all
ret