forked from DFHack/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-unit.lua
1217 lines (1064 loc) · 40.7 KB
/
create-unit.lua
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Creates a unit. Beta; use at own risk.
-- Originally created by warmist
-- Significant contributions over time by Boltgun, Dirst, Expwnent, lethosor, mifki, Putnam and Atomic Chicken.
--[[
TODO
confirm body size is computed appropriately for different ages / life stages
incarnate pre-existing historical figures
some sort of invasion helper script
set invasion_id, etc
announcement for fake natural birth if appropriate
option to attach to an existing wild animal population
option to attach to a map feature
]]
--@ module = true
local usage = [====[
modtools/create-unit
====================
Creates a unit. Usage::
-race raceName
(obligatory)
Specify the race of the unit to be created.
examples:
DWARF
HUMAN
-caste casteName
Specify the caste of the unit to be created.
If omitted, the caste is randomly selected.
examples:
MALE
FEMALE
DEFAULT
-domesticate
Tames the unit if it lacks the CAN_LEARN and CAN_SPEAK tokens.
-civId id
Make the created unit a member of the specified civilisation
(or none if id = -1). If id is \\LOCAL, make it a member of the
civ associated with the fort; otherwise id must be an integer
-groupId id
Make the created unit a member of the specified group
(or none if id = -1). If id is \\LOCAL, make it a member of the
group associated with the fort; otherwise id must be an integer
-setUnitToFort
Sets the groupId and civId to those of the player in Fortress mode.
Equivalent to -civId \\LOCAL and -groupId \\LOCAL.
-name entityRawName
Set the unit's name to be a random name appropriate for the
given entity. \\LOCAL can be specified instead to automatically
use the fort group entity in fortress mode only.
examples:
MOUNTAIN
EVIL
-nick nickname
This can be included to nickname the unit.
Replace "nickname" with the desired name.
-age howOld
This can be included to specify the unit's age.
Replace "howOld" with a (non-negative) number.
The unit's age is set randomly if this is omitted.
-equip [ ITEM:MATERIAL:QUANTITY ... ]
This can be included to create items and equip them onto
the created unit.
This is carried out via the same logic used in arena mode,
so equipment will always be sized correctly and placed
on what the game deems to be appropriate bodyparts.
Clothing is also layered in the appropriate order.
Note that this currently comes with some limitations,
such as an inability to specify item quality
and objects not being placed in containers
(for example, arrows are not placed in quivers).
Item quantity defaults to 1 if omitted.
When spaces are included in the item or material name,
the entire item description should be enclosed in
quotation marks. This can also be done to increase
legibility when specifying multiple items.
examples:
-equip [ RING:CREATURE:DWARF:BONE:3 ]
3 dwarf bone rings
-equip [ ITEM_WEAPON_PICK:INORGANIC:IRON ]
1 iron pick
-equip [ "ITEM_SHIELD_BUCKLER:PLANT:OAK:WOOD" "AMULET:AMBER" ]
1 oaken buckler and 1 amber amulet
-skills [ SKILL:LEVEL ... ]
This can be included to add skills to the created unit.
Specify a skill token followed by a skill level value.
Look up "Skill Token" and "Skill" on the DF Wiki for a list
of valid tokens and levels respectively.
Note that the skill level provided must be a number greater than 0.
If the unit possesses a matching natural skill, this is added to it.
Quotation marks can be added for legibility as explained above.
example:
-skill [ SNEAK:1 EXTRACT_STRAND:15 ]
novice ambusher, legendary strand extractor
-profession token
This can be included to set the unit's profession.
Replace "token" with a Unit Type Token (check the DF Wiki for a list).
For skill-based professions, it is recommended to give the unit
the appropriate skill set via -skills.
This can also be used to make animals trained for war/hunting.
Note that this will be overridden if the unit has been given the age
of a baby or child, as these have a special "profession" set.
Using this for setting baby/child status is not recommended;
this should be done via -age instead.
examples:
STRAND_EXTRACTOR
MASTER_SWORDSMAN
TRAINED_WAR
-customProfession name
This can be included to give the unit a custom profession name.
Enclose the name in quotation marks if it includes spaces.
example:
-customProfession "Destroyer of Worlds"
-duration ticks
If this is included, the unit will vanish in a puff of smoke
once the specified number of ticks has elapsed.
Replace "ticks" with an integer greater than 0.
Note that the unit's equipment will not vanish.
-quantity howMany
This can be included to create multiple creatures simultaneously.
Replace "howMany" with the desired number of creatures.
Quantity defaults to 1 if this is omitted.
-location [ x y z ]
(obligatory)
Specify the coordinates where you want the unit to appear.
-locationRange [ x_offset y_offset z_offset ]
If included, the unit will be spawned at a random location
within the specified range relative to the target -location.
z_offset defaults to 0 if omitted.
When creating multiple units, the location is randomised each time.
example:
-locationRange [ 4 3 1 ]
attempts to place the unit anywhere within
-4 to +4 tiles on the x-axis
-3 to +3 tiles on the y-axis
-1 to +1 tiles on the z-axis
from the specified -location coordinates
-locationType type
May be used with -locationRange
to specify what counts as a valid tile for unit spawning.
Unit creation will not occur if no valid tiles are available.
Replace "type" with one of the following:
Walkable
units will only be placed on walkable ground tiles
this is the default used if -locationType is omitted
Open
open spaces are also valid spawn points
this is intended for flying units
Any
all tiles, including solid walls, are valid
this is only recommended for ghosts not carrying items
-flagSet [ flag1 flag2 ... ]
This can be used to set the specified unit flags to true.
Flags may be selected from:
df.unit_flags1
df.unit_flags2
df.unit_flags3
df.unit_flags4
example:
flagSet [ announce_titan ]
causes an announcement describing the unit to appear
when it is discovered ("[Unit] has come! ...")
-flagClear [ flag1 flag2 ... ]
As above, but sets the specified unit flags to false.
]====]
local utils = require 'utils'
function createUnit(raceStr, casteStr, pos, locationRange, locationType, age, domesticate, civ_id, group_id, entityRawName, nickname, vanishDelay, quantity, equip, skills, profession, customProfession, flagSet, flagClear)
-- creates the desired unit(s) at the specified location
-- returns a table containing the created unit(s)
if not pos then
qerror("Location not specified!") -- check repeated for module usage
end
if not dfhack.maps.isValidTilePos(pos) then
qerror("Invalid location!")
end
if locationType and locationType ~= 'Walkable' and locationType ~= 'Open' and locationType ~= 'Any' then
qerror('Invalid location type: ' .. locationType)
end
local locationChoices
if locationRange then
locationType = locationType or 'Walkable'
locationChoices = getLocationChoices(pos, locationRange.offset_x, locationRange.offset_y, locationRange.offset_z)
end
if age then
if not tonumber(age) or tonumber(age) < 0 then
qerror('Invalid age (must be 0 or greater): ' .. tostring(age))
end
end
if vanishDelay then
if not tonumber(vanishDelay) or tonumber(vanishDelay) < 1 then
qerror('Invalid duration (must be a number greater than 0): ' .. tostring(vanishDelay))
end
end
if civ_id then
if not tonumber(civ_id) then
qerror('Invalid civId (must be a number): ' .. tostring(civ_id))
end
civ_id = tonumber(civ_id)
if civ_id ~= -1 and not df.historical_entity.find(civ_id) then
qerror('Civilisation not found: ' .. tostring(civ_id))
end
end
if group_id then
if not tonumber(group_id) then
qerror('Invalid groupId (must be a number): ' .. tostring(group_id))
end
group_id = tonumber(group_id)
if group_id ~= -1 and not df.historical_entity.find(civ_id) then
qerror('Group not found: ' .. tostring(group_id))
end
end
if nickname and type(nickname) ~= 'string' then
qerror('Invalid nickname: ' .. tostring(nickname))
end
if customProfession and (type(customProfession) ~= 'string') then
qerror('Invalid custom profession: ' .. tostring(customProfession))
end
if profession and not df.profession[profession] then
qerror('Invalid profession: ' .. tostring(profession))
end
local spawnNumber = 1
if quantity then
spawnNumber = tonumber(quantity)
if not spawnNumber or spawnNumber < 1 then
qerror('Invalid spawn quantity (must be a number greater than 0): ' .. tostring(quantity))
end
end
local equipDetails
if equip then
equipDetails = {}
for _, equipStr in ipairs(equip) do
table.insert(equipDetails, extractEquipmentDetail(equipStr))
end
end
local skillDetails
if skills then
skillDetails = {}
for _, skillStr in ipairs(skills) do
table.insert(skillDetails, extractSkillDetail(skillStr))
end
end
local race_id, caste_id, caste_id_choices = getRaceCasteIDs(raceStr, casteStr)
return createUnitBase(race_id, caste_id, caste_id_choices, pos, locationChoices, locationType, tonumber(age), domesticate, civ_id, group_id, entityRawName, nickname, tonumber(vanishDelay), equipDetails, skillDetails, profession, customProfession, flagSet, flagClear, spawnNumber)
end
function createUnitBase(...)
local old_gametype = df.global.gametype
local old_mode = df.global.ui.main.mode
local old_popups = {} --as:df.popup_message[]
for _, popup in pairs(df.global.world.status.popups) do
table.insert(old_popups, popup)
end
df.global.world.status.popups:resize(0) -- popups would prevent us from opening the creature creation menu, so remove them temporarily
local ok, ret = dfhack.pcall(createUnitInner, ...)
df.global.gametype = old_gametype
df.global.ui.main.mode = old_mode
for _, popup in pairs(old_popups) do
df.global.world.status.popups:insert('#', popup)
end
if not ok then
error(ret)
end
return ret
end
function createUnitInner(race_id, caste_id, caste_id_choices, pos, locationChoices, locationType, age, domesticate, civ_id, group_id, entityRawName, nickname, vanishDelay, equipDetails, skillDetails, profession, customProfession, flagSet, flagClear, spawnNumber)
local gui = require 'gui'
local view_x = df.global.window_x
local view_y = df.global.window_y
local view_z = df.global.window_z
local cursor = copyall(df.global.cursor)
local isArena = dfhack.world.isArena()
local arenaSpawn = df.global.world.arena_spawn
local oldSpawnType
local oldSpawnFilter
oldSpawnType = arenaSpawn.type
arenaSpawn.type = 0 -- selects the creature at index 0 when the arena spawn screen is produced
oldSpawnFilter = arenaSpawn.filter
arenaSpawn.filter = "" -- clear filter to prevent it from messing with the selection
-- Clear arena spawn data to avoid interference:
local oldInteractionEffect
oldInteractionEffect = arenaSpawn.interaction
arenaSpawn.interaction = -1
local oldSpawnTame
oldSpawnTame = arenaSpawn.tame
arenaSpawn.tame = df.world.T_arena_spawn.T_tame.NotTame -- prevent interference by the tame/mountable setting (which isn't particularly useful as it only appears to set unit.flags1.tame)
local equipment = arenaSpawn.equipment
local old_item_types = {} --as:df.item_type[]
for _, item_type in pairs(equipment.item_types) do
table.insert(old_item_types, item_type)
end
equipment.item_types:resize(0)
local old_item_subtypes = {} --as:number[]
for _, item_subtype in pairs(equipment.item_subtypes) do
table.insert(old_item_subtypes, item_subtype)
end
equipment.item_subtypes:resize(0)
local old_item_mat_types = {} --as:number[]
for _, item_mat_type in pairs(equipment.item_materials.mat_type) do
table.insert(old_item_mat_types, item_mat_type)
end
equipment.item_materials.mat_type:resize(0)
local old_item_mat_indexes = {} --as:number[]
for _, item_mat_index in pairs(equipment.item_materials.mat_index) do
table.insert(old_item_mat_indexes, item_mat_index)
end
equipment.item_materials.mat_index:resize(0)
local old_item_counts = {} --as:number[]
for _, item_count in pairs(equipment.item_counts) do
table.insert(old_item_counts, item_count)
end
equipment.item_counts:resize(0)
local old_skills = {} --as:number[]
for _, skill in ipairs(equipment.skills) do
table.insert(old_skills, skill)
end
equipment.skills:resize(0)
local old_skill_levels = {} --as:number[]
for _, skill_level in ipairs(equipment.skill_levels) do
table.insert(old_skill_levels, skill_level)
end
equipment.skill_levels:resize(0)
-- Spawn the creature:
arenaSpawn.race:insert(0, race_id) -- place at index 0 to allow for straightforward selection as described above. The rest of the list need not be cleared.
if caste_id then
arenaSpawn.caste:insert(0, caste_id) -- if not specificied, caste_id is randomly selected and inserted during the spawn loop below, as otherwise creating multiple creatures simultaneously would result in them all being of the same caste.
end
arenaSpawn.creature_cnt:insert('#', 0)
local curViewscreen = dfhack.gui.getCurViewscreen()
local dwarfmodeScreen = df.viewscreen_dwarfmodest:new() -- the viewscreen present in arena "overseer" mode
curViewscreen.child = dwarfmodeScreen
dwarfmodeScreen.parent = curViewscreen
df.global.ui.main.mode = df.ui_sidebar_mode.LookAround -- produce the cursor
df.global.gametype = df.game_type.DWARF_ARENA
if not locationChoices then -- otherwise randomise the cursor location for every unit spawned in the loop below
-- move cursor to location instead of moving unit later, corrects issue of missing mapdata when moving the created unit.
df.global.cursor.x = tonumber(pos.x)
df.global.cursor.y = tonumber(pos.y)
df.global.cursor.z = tonumber(pos.z)
end
if equipDetails then
for _, equip in ipairs(equipDetails) do
equipment.item_types:insert('#', equip.itemType)
equipment.item_subtypes:insert('#', equip.subType)
equipment.item_materials.mat_type:insert('#', equip.matType)
equipment.item_materials.mat_index:insert('#', equip.matIndex)
equipment.item_counts:insert('#', equip.quantity)
end
end
if skillDetails then
for _, skill in ipairs(skillDetails) do
equipment.skills:insert('#', skill.skill)
equipment.skill_levels:insert('#', skill.level)
end
end
local createdUnits = {}
for n = 1, spawnNumber do -- loop here to avoid having to handle spawn data each time when creating multiple units
if not caste_id then -- choose a random caste ID each time
arenaSpawn.caste:insert(0, caste_id_choices[math.random(1, #caste_id_choices)])
end
if locationChoices then
-- select a random spawn position within the specified location range, if available
local randomPos
for n = 1, #locationChoices do
local i = math.random(1, #locationChoices)
if locationType == 'Any' or isValidSpawnLocation(locationChoices[i], locationType) then
randomPos = locationChoices[i]
break
else
table.remove(locationChoices, i) -- remove invalid positions from the list to optimise subsequent spawning sequences
end
end
if randomPos then
df.global.cursor.x = tonumber(randomPos.x)
df.global.cursor.y = tonumber(randomPos.y)
df.global.cursor.z = tonumber(randomPos.z)
else
break -- no valid tiles available; terminate the spawn loop without creating any units
end
end
gui.simulateInput(dwarfmodeScreen, 'D_LOOK_ARENA_CREATURE') -- open the arena spawning menu
local spawnScreen = dfhack.gui.getCurViewscreen() -- df.viewscreen_layer_arena_creaturest
gui.simulateInput(spawnScreen, 'SELECT') -- create the selected creature
if not caste_id then
arenaSpawn.caste:erase(0)
end
-- Process the created unit:
local unit = df.unit.find(df.global.unit_next_id-1)
table.insert(createdUnits, unit)
processNewUnit(unit, age, domesticate, civ_id, group_id, entityRawName, nickname, vanishDelay, profession, customProfession, flagSet, flagClear, isArena)
end
dfhack.screen.dismiss(dwarfmodeScreen)
df.global.window_x = view_x -- view moves whilst spawning units, so restore it here
df.global.window_y = view_y
df.global.window_z = view_z
df.global.cursor:assign(cursor) -- cursor sometimes persists in adventure mode, so ensure that it's reset
-- Restore arena spawn data:
arenaSpawn.race:erase(0)
if caste_id then
arenaSpawn.caste:erase(0)
end
arenaSpawn.creature_cnt:erase(0)
arenaSpawn.filter = oldSpawnFilter
arenaSpawn.type = oldSpawnType
arenaSpawn.interaction = oldInteractionEffect
arenaSpawn.tame = oldSpawnTame
if equipDetails then
equipment.item_types:resize(0)
equipment.item_subtypes:resize(0)
equipment.item_materials.mat_type:resize(0)
equipment.item_materials.mat_index:resize(0)
equipment.item_counts:resize(0)
end
if skillDetails then
equipment.skills:resize(0)
equipment.skill_levels:resize(0)
end
for _,i in pairs(old_item_types) do
equipment.item_types:insert('#',i)
end
for _,i in pairs(old_item_subtypes) do
equipment.item_subtypes:insert('#',i)
end
for _,i in pairs(old_item_mat_types) do
equipment.item_materials.mat_type:insert('#',i)
end
for _,i in pairs(old_item_mat_indexes) do
equipment.item_materials.mat_index:insert('#',i)
end
for _,i in pairs(old_item_counts) do
equipment.item_counts:insert('#',i)
end
for _,i in ipairs(old_skills) do
equipment.skills:insert('#',i)
end
for _,i in ipairs(old_skill_levels) do
equipment.skill_levels:insert('#',i)
end
return createdUnits -- table containing the created unit(s) (intended for module usage)
end
function getLocationChoices(pos, offset_x, offset_y, offset_z)
local spawnCoords = {}
local min_x = pos.x - offset_x
local max_x = pos.x + offset_x
local min_y = pos.y - offset_y
local max_y = pos.y + offset_y
local min_z = pos.z - offset_z
local max_z = pos.z + offset_z
local map = df.global.world.map
local map_x = map.x_count-1 -- maximum local coordinates on the loaded map
local map_y = map.y_count-1
local map_z = map.z_count-1
for x = min_x >= 0 and min_x or 0, max_x <= map_x and max_x or map_x do
for y = min_y >= 0 and min_y or 0, max_y <= map_y and max_y or map_y do
for z = min_z >= 0 and min_z or 0, max_z <= map_z and max_z or map_z do
table.insert(spawnCoords,{x = x, y = y, z = z})
end
end
end
return spawnCoords
end
function isValidSpawnLocation(pos, locationType)
if not dfhack.maps.isValidTilePos(pos) then
return false
end
local tiletype = dfhack.maps.getTileBlock(pos.x, pos.y, pos.z).tiletype[pos.x%16][pos.y%16]
local tileShapeAttrs = df.tiletype_shape.attrs[df.tiletype.attrs[tiletype].shape]
if locationType == 'Open' then
if tileShapeAttrs.basic_shape == df.tiletype_shape_basic.Open then
return true
end
return false
elseif locationType == 'Walkable' then
if tileShapeAttrs.walkable and tileShapeAttrs.basic_shape ~= df.tiletype_shape_basic.Open then
return true
end
return false
end
end
function getRaceCasteIDs(raceStr, casteStr)
-- Takes a race name and a caste name and returns the appropriate race and caste IDs.
-- Returns a table of valid caste IDs if casteStr is omitted.
if not raceStr then
qerror("Race not specified!")
end
local race
local raceIndex
for i,c in ipairs(df.global.world.raws.creatures.all) do
if c.creature_id == raceStr then
race = c
raceIndex = i
break
end
end
if not race then
qerror('Invalid race: ' .. raceStr)
end
local casteIndex
local caste_id_choices = {} --as:number[]
if casteStr then
for i,c in ipairs(race.caste) do
if c.caste_id == casteStr then
casteIndex = i
break
end
end
if not casteIndex then
qerror('Invalid caste: ' .. casteStr)
end
else
for i,c in ipairs(race.caste) do
table.insert(caste_id_choices, i)
end
end
return raceIndex, casteIndex, caste_id_choices
end
local function allocateNewChunk(hist_entity)
hist_entity.save_file_id = df.global.unit_chunk_next_id
df.global.unit_chunk_next_id = df.global.unit_chunk_next_id+1
hist_entity.next_member_idx = 0
print("allocating chunk:",hist_entity.save_file_id)
end
local function allocateIds(nemesis_record,hist_entity)
if hist_entity.next_member_idx == 100 then
allocateNewChunk(hist_entity)
end
nemesis_record.save_file_id = hist_entity.save_file_id
nemesis_record.member_idx = hist_entity.next_member_idx
hist_entity.next_member_idx = hist_entity.next_member_idx+1
end
function createFigure(unit,he,he_group)
local hf = df.historical_figure:new()
hf.id = df.global.hist_figure_next_id
df.global.hist_figure_next_id = df.global.hist_figure_next_id+1
hf.unit_id = unit.id
hf.nemesis_id = -1
hf.race = unit.race
hf.caste = unit.caste
hf.profession = unit.profession
hf.sex = unit.sex
hf.name:assign(unit.name)
hf.appeared_year = df.global.cur_year
hf.born_year = unit.birth_year
hf.born_seconds = unit.birth_time
hf.curse_year = unit.curse_year
hf.curse_seconds = unit.curse_time
hf.birth_year_bias = unit.birth_year_bias
hf.birth_time_bias = unit.birth_time_bias
hf.old_year = unit.old_year
hf.old_seconds = unit.old_time
hf.died_year = -1
hf.died_seconds = -1
hf.civ_id = unit.civ_id
hf.population_id = unit.population_id
hf.breed_id = -1
hf.cultural_identity = unit.cultural_identity
hf.family_head_id = -1
df.global.world.history.figures:insert("#", hf)
hf.info = df.historical_figure_info:new()
hf.info.whereabouts = df.historical_figure_info.T_whereabouts:new()
hf.info.whereabouts.death_condition_parameter_1 = -1
hf.info.whereabouts.death_condition_parameter_2 = -1
-- set values that seem related to state and do event
--change_state(hf, dfg.ui.site_id, region_pos)
--let's skip skills for now
--local skills = df.historical_figure_info.T_skills:new() -- skills snap shot
-- ...
-- note that innate skills are automaticaly set by DF
hf.info.skills = {new=true}
if he then
he.histfig_ids:insert('#', hf.id)
he.hist_figures:insert('#', hf)
hf.entity_links:insert("#",{new=df.histfig_entity_link_memberst,entity_id=unit.civ_id,link_strength=100})
--add entity event
local hf_event_id = df.global.hist_event_next_id
df.global.hist_event_next_id = df.global.hist_event_next_id+1
df.global.world.history.events:insert("#",{new=df.history_event_add_hf_entity_linkst,year=unit.birth_year,
seconds=unit.birth_time,id=hf_event_id,civ=hf.civ_id,histfig=hf.id,link_type=0})
end
if he_group and he_group ~= he then
he_group.histfig_ids:insert('#', hf.id)
he_group.hist_figures:insert('#', hf)
hf.entity_links:insert("#",{new=df.histfig_entity_link_memberst,entity_id=he_group.id,link_strength=100})
end
local soul = unit.status.current_soul
if soul then
hf.orientation_flags:assign(soul.orientation_flags)
end
unit.flags1.important_historical_figure = true
unit.flags2.important_historical_figure = true
unit.hist_figure_id = hf.id
unit.hist_figure_id2 = hf.id
return hf
end
function createNemesis(unit,civ_id,group_id)
local id = df.global.nemesis_next_id
local nem = df.nemesis_record:new()
nem.id = id
nem.unit_id = unit.id
nem.unit = unit
nem.flags:resize(31)
nem.unk10 = -1
nem.unk11 = -1
nem.unk12 = -1
df.global.world.nemesis.all:insert("#",nem)
df.global.nemesis_next_id = id+1
unit.general_refs:insert("#",{new = df.general_ref_is_nemesisst, nemesis_id = id})
nem.save_file_id = -1
local he
if civ_id and civ_id ~= -1 then
he = df.historical_entity.find(civ_id)
he.nemesis_ids:insert("#",id)
he.nemesis:insert("#",nem)
allocateIds(nem,he)
end
local he_group
if group_id and group_id ~= -1 then
he_group = df.historical_entity.find(group_id)
end
if he_group then
he_group.nemesis_ids:insert("#",id)
he_group.nemesis:insert("#",nem)
end
nem.figure = unit.hist_figure_id ~= -1 and df.historical_figure.find(unit.hist_figure_id) or createFigure(unit,he,he_group) -- the histfig check is there just in case this function is called by another script to create nemesis data for a historical figure which somehow lacks it
nem.figure.nemesis_id = id
return nem
end
function nameUnit(unit, entityRawName)
--pick a random appropriate name
--choose three random words in the appropriate things
local entity_raw
if entityRawName then
for k,v in ipairs(df.global.world.raws.entities) do
if v.code == entityRawName then
entity_raw = v
break
end
end
end
if not entity_raw then
qerror('Invalid entity raw name: ' .. entityRawName)
end
local translation = entity_raw.translation
local translationIndex
for k,v in ipairs(df.global.world.raws.language.translations) do
if v.name == translation then
translationIndex = k
break
end
end
local language_word_table = entity_raw.symbols.symbols1[0] --educated guess
function randomWord()
local index = math.random(0, #language_word_table.words[0] - 1)
return index
end
local firstName = randomWord()
local lastName1 = randomWord()
local lastName2 = randomWord()
local name = unit.name
name.words[0] = language_word_table.words[0][lastName1]
name.parts_of_speech[0] = language_word_table.parts[0][lastName1]
name.words[1] = language_word_table.words[0][lastName2]
name.parts_of_speech[1] = language_word_table.parts[0][lastName2]
local language = nil
for _, lang in pairs(df.global.world.raws.language.translations) do
if lang.name == entity_raw.translation then
language = lang
end
end
if language then
name.first_name = language.words[firstName].value
else
name.first_name = df.language_word.find(language_word_table.words[0][firstName]).forms[language_word_table.parts[0][firstName]]
end
name.has_name = true
name.language = translationIndex
if unit.status.current_soul then
unit.status.current_soul.name:assign(name)
end
local hf = df.historical_figure.find(unit.hist_figure_id)
if hf then
hf.name:assign(name)
end
end
function getItemTypeFromStr(itemTypeStr)
--returns itemType and subType when passed a string like "ITEM_WEAPON_CROSSBOW" or "BOULDER"
local itemType = df.item_type[itemTypeStr]
if itemType then
return itemType, -1
end
for i = 0, df.item_type._last_item do
local subTypeCount = dfhack.items.getSubtypeCount(i)
if subTypeCount ~= -1 then
for subType = 0, subTypeCount-1 do
if dfhack.items.getSubtypeDef(i, subType).id == itemTypeStr then
return i, subType
end
end
end
end
qerror("Invalid item type: " .. itemTypeStr)
end
function extractEquipmentDetail(equipmentStr)
-- equipmentStr example: "ITEM_SHIELD_BUCKLER:PLANT:OAK:WOOD:2"
local equipDetail = {}
local raw = {}
for str in string.gmatch(equipmentStr, '([^:]+)') do -- break it up at colons
table.insert(raw, str) -- and list the segments here
end
if #raw < 2 then
qerror('Insufficient equipment details provided: ' .. equipmentStr)
end
equipDetail.itemType, equipDetail.subType = getItemTypeFromStr(raw[1])
local quantityIdx
local matStr = raw[2]
if matStr == 'INORGANIC' or matStr == 'PLANT' or matStr == 'CREATURE' then
if not raw[3] then
print(equipmentStr) -- print this first to help modders locate the issue
qerror('Invalid equipment material (missing detail): ' .. matStr)
end
if matStr == 'INORGANIC' then
-- example: INORGANIC:IRON
matStr = matStr .. ":" .. raw[3]
quantityIdx = 4 -- expected position of the quantity str
else
-- example: PLANT:OAK:WOOD
-- example: CREATURE:DWARF:BONE
matStr = matStr .. ":" .. raw[3] -- placed here so as to make it show up in the following qerror message
if not raw[4] then
print(equipmentStr)
qerror('Invalid equipment material (missing detail): ' .. matStr)
end
matStr = matStr .. ":" .. raw[4]
quantityIdx = 5
end
else -- either an inbuilt material or an error
-- example: GLASS_CLEAR
quantityIdx = 3
end
local matInfo = dfhack.matinfo.find(matStr)
if not matInfo then
print(equipmentStr)
qerror('Invalid equipment material: ' .. matStr)
end
equipDetail.matType = matInfo.type
equipDetail.matIndex = matInfo.index
if not raw[quantityIdx] then -- quantity not specified, default to 1
equipDetail.quantity = 1
else
local quantity = tonumber(raw[quantityIdx])
if not quantity or quantity < 0 then
print(equipmentStr)
qerror("Invalid equipment count: " .. raw[quantityIdx])
end
equipDetail.quantity = quantity
end
return equipDetail
end
function extractSkillDetail(skillStr)
local skillDetail = {}
local raw = {}
for str in string.gmatch(skillStr, '([^:]+)') do
table.insert(raw, str)
end
if #raw < 2 then
qerror('Insufficient skill details provided: ' .. skillStr)
end
local skill = df.job_skill[raw[1]]
if not skill then
qerror('Invalid skill token: ' .. raw[1])
end
skillDetail.skill = skill
local level = tonumber(raw[2])
if not level or level < 0 then
qerror('Invalid skill level (must be a number greater than 0): ' .. raw[2])
end
skillDetail.level = level
return skillDetail
end
function processNewUnit(unit, age, domesticate, civ_id, group_id, entityRawName, nickname, vanishDelay, profession, customProfession, flagSet, flagClear, isArena) -- isArena boolean is used for determining whether or not the arena name should be cleared
if entityRawName and type(entityRawName) == 'string' then
nameUnit(unit, entityRawName)
elseif not isArena then -- arena mode ONLY displays the first_name of units; removing it would result in a blank space where you'd otherwise expect the caste name to show up
unit.name.first_name = '' -- removes the string of numbers produced by the arena spawning process
unit.name.has_name = false
if unit.status.current_soul then
unit.status.current_soul.name.has_name = false
end
end
if nickname and type(nickname) == 'string' then
dfhack.units.setNickname(unit, nickname)
end
if customProfession then
unit.custom_profession = tostring(customProfession)
end
if profession then
unit.profession = df.profession[profession] -- will be overridden by setAge() below if the unit is turned into a BABY or CHILD
end
if tonumber(civ_id) then
unit.civ_id = civ_id
end
createNemesis(unit, tonumber(civ_id), tonumber(group_id))
setAge(unit, age) -- run regardless of whether or not age has been specified so as to set baby/child status
induceBodyComputations(unit)
if domesticate then
domesticateUnit(unit)
elseif not civ_id then
wildUnit(unit)
end
if vanishDelay then
setVanishCountdown(unit, vanishDelay)
end
setEquipmentOwnership(unit)
enableUnitLabors(unit, true, true)
handleUnitFlags(unit,flagSet,flagClear)
end
function setAge(unit, age)
-- Shifts the unit's birth and death dates to match the specified age.
-- Also checks for [BABY] and [CHILD] tokens and turns the unit into a baby/child if age-appropriate.
local hf = df.historical_figure.find(unit.hist_figure_id)
if age then
if not tonumber(age) or age < 0 then -- this check is repeated for the sake of module usage
qerror("Invalid age: " .. age)
end
-- Change birth and death dates:
if age == 0 then
unit.birth_time = df.global.cur_year_tick
end
local oldYearDelta = unit.old_year - unit.birth_year -- the unit's natural lifespan
unit.birth_year = df.global.cur_year - age
if unit.old_year ~= -1 then
unit.old_year = unit.birth_year + oldYearDelta
end
if hf then
hf.born_year = unit.birth_year
hf.born_seconds = unit.birth_time
hf.old_year = unit.old_year
hf.old_seconds = unit.old_time
end
end
-- Turn into a child or baby if appropriate:
local getAge = age or dfhack.units.getAge(unit,true)
local cr = df.creature_raw.find(unit.race).caste[unit.caste]
if cr.flags.HAS_BABYSTATE and (getAge < cr.misc.baby_age) then
unit.profession = df.profession.BABY
--unit.profession2 = df.profession.BABY
unit.mood = df.mood_type.Baby
elseif cr.flags.HAS_CHILDSTATE and (getAge < cr.misc.child_age) then
unit.profession = df.profession.CHILD
--unit.profession2 = df.profession.CHILD
end
if hf then
hf.profession = unit.profession
end
end
function induceBodyComputations(unit)
--these flags are an educated guess of how to get the game to compute sizes correctly: use -flagSet and -flagClear arguments to override or supplement
unit.flags2.calculated_nerves = false
unit.flags2.calculated_bodyparts = false
unit.flags3.body_part_relsize_computed = false
unit.flags3.size_modifier_computed = false
unit.flags3.weight_computed = false
end
function domesticateUnit(unit)
-- If a friendly animal, make it domesticated. From Boltgun & Dirst
local casteFlags = unit.enemy.caste_flags
if not(casteFlags.CAN_SPEAK and casteFlags.CAN_LEARN) then
-- Fix friendly animals (from Boltgun)
unit.flags2.resident = false
unit.population_id = -1