forked from DFHack/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dwarf-op.lua
1344 lines (1205 loc) · 46.7 KB
/
dwarf-op.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
-- Optimizes dwarves for labor. Very flexible. Very robust. Check the help.
-- written by josh cooper(cppcooper) [created: Dec. 2017 | last modified: 2020-03-01]
print(dfhack.current_script_name() .. " v1.4")
utils ={}
utils = require('utils')
json = require('json')
local rng = require('plugins.cxxrandom')
local engineID = rng.MakeNewEngine()
local dorf_tables = reqscript('dorf_tables')
cloned = {} --assurances I'm sure
cloned = {
distributions = utils.clone(dorf_tables.job_distributions, true),
attrib_levels = utils.clone(dorf_tables.attrib_levels, true),
types = utils.clone(dorf_tables.types, true),
jobs = utils.clone(dorf_tables.jobs, true),
professions = utils.clone(dorf_tables.professions, true),
}
protected_dwarf_signals = {'.', ','}
local validArgs = utils.invert({
'help',
'debug',
'show',
'reset',
'resetall',
'select', --highlighted --all --named --unnamed --employed --optimized --unoptimized --protected --unprotected --drunks --jobs
'clean',
'clear',
'reroll',
'optimize',
'applyjobs',
'applyprofessions',
'applytypes',
'renamejob'
})
local args = utils.processArgs({...}, validArgs)
local help = [====[
dwarf-op
========
Dwarf optimization is a script designed to provide a robust solution
to hacking dwarves to be better at work. The primary use case is as follows:
1) take a dwarf
2) delete their ability to do anything, even walk (job skills, phyiscal/mental attributes)
3) load the job distribution table from dorf_tables
4) update values in said table so the table accurately represents the distribution of your dwarves
5) pick an under-represented job from the table
6) apply the job to the dwarf, which means:
- apply professions
- provide custom profession name
- add job skills
- apply dwarf types
- etc.
Beyond this use case of optimizing dwarves according to the tables in
`dorf_tables`, this script makes each step in the process available to use
separately, if you so choose.
There are two basic steps to using this script: selecting a subset of your dwarves,
and running commands on those dwarves.
Usage::
dwarf-op -help
dwarf-op -select <select-option> -<command> <args>
Examples::
dwarf-op -select [ jobs Trader Miner Leader Rancher ] -applytype adaptable
dwarf-op -select all -clear -optimize
dwarf-op -select pall -clear -optimize
dwarf-op -select optimized -reroll
dwarf-op -select named -reroll inclusive -applyprofession RECRUIT
**Select options:**
.. note::
Prepend the letter ``p`` to any option to include protected dwarves in your selection
:(none): same as typing '-select highlighted'
:all: selects all dwarves.
:highlighted: selects only the in-game highlighted dwarf (from any screen).
[Ignores protection status]
:<name>: selects any dwarf with <name> in their name or nickname.
(sub-string match) [Ignores protection status]
:named: selects dwarves with user-given names.
:unnamed: selects dwarves without user-given names.
:employed: selects dwarves with custom professions. Excludes optimized dwarves.
:optimized: selects dwarves based on session data. Dwarves who have been
optimized should be listed in this data.
:unoptimized: selects any dwarves that don't appear in session data.
:protected: selects any dwarves which use protection signals in their name
or profession. (i.e. ``.``, ``,``)
:unprotected: selects any dwarves which don't use protection signals in their
name or profession.
:drunks: selects any dwarves which are currently zeroed, or were
originally drunks as their profession.
:jobs: selects any dwarves with the listed jobs. This will only match
with custom professions, or optimized dwarves (for optimized
dwarves see jobs in `dorf_tables`).
Usage::
dwarf-op -select [ jobs job1 job2 etc. ]
Example::
dwarf-op -select [ jobs Miner Trader ]
:waves: selects dwarves from the specified migration waves. Waves are
enumerated starting at 0 and increasing by 1 with each wave. The
waves go by season and year and thus should match what you see
in `list-waves` or Dwarf Therapist. It is recommended that you
``-show`` the selected dwarves before modifying.
Example::
dwarf-op -select [ waves 0 1 3 5 7 13 ]
**General commands:**
- ``-reset``: deletes json file containing session data (bug: might not delete
session data)
- ``-resetall``: deletes both json files. session data and existing persistent
data (bug: might not delete session data)
- ``-show``: displays affected dwarves (id, name, migration wave, primary job).
Useful for previewing selected dwarves before modifying them, or looking up
the migration wave number for a group of dwarves.
**Dwarf commands:**
``clean <value>``: Cleans selected dwarves.
Checks for skills with a rating of ``<value>`` and
deletes them from the dwarf's skill list
``-clear``: Zeroes selected dwarves, or zeroes all dwarves if no selection is given.
No attributes, no labours. Assigns ``DRUNK`` profession.
``-reroll [inclusive]``: zeroes selected dwarves, then rerolls that dwarf based on its job.
- Ignores dwarves with unlisted jobs.
- optional argument: ``inclusive`` - means your dorf(s) get the best of N rolls.
- See attrib_levels table in `dorf_tables` for ``p`` values describing the
normal distribution of stats (each p value has a sub-distribution, which
makes the bell curve not so bell-shaped). Labours do not follow the same
stat system and are more uniformly random, which are compensated for in
the description of jobs/professions.
``-optimize``: Performs a job search for unoptimized dwarves.
Each dwarf will be found a job according to the
job_distribution table in `dorf_tables`.
``-applyjobs``: Applies the listed jobs to the selected dwarves.
- List format: ``[ job1 job2 jobn ]`` (brackets and jobs all separated by spaces)
- See jobs table in `dorf_tables` for available jobs."
``-applyprofessions``: Applies the listed professions to the selected dwarves.
- List format: ``[ prof1 prof2 profn ]`` (brackets and professions all separated by spaces)
- See professions table in `dorf_tables` for available professions.
``-applytypes``: Applies the listed types to the selected dwarves.
- List format: ``[ type1 type2 typen ]`` (brackets and types all separated by spaces)
- See dwf_types table in `dorf_tables` for available types.
``renamejob <name>``: Renames the selected dwarves' custom profession to whatever is specified
**Other Arguments:**
``-help``: displays this help information.
``-debug``: enables debugging print lines
]====]
if args.debug and tonumber(args.debug) >= 0 then print("Debug info [ON]") end
if args.select and args.select == 'optimized' then
if args.optimize and not args.clear then
error("Invalid arguments detected. You've selected only optimized dwarves, and are attempting to optimize them without clearing them. This will not work, so I'm warning you about it with this lovely error.")
end
end
--[[--
The persistent data contains information on current allocations
FileData: {
Dwarves : {
id : {
job : dorf_table.dorf_jobs[job],
professions : [
dorf_table.professions[prof],
]
},
},
dorf_table.dorf_jobs[job] : {
count : int,
profs : {
dorf_table.professions[prof] : {
count : int,
p : float --intended ratio of profession in job
},
}
}
}
--]]--
function LoadPersistentData()
local gamePath = dfhack.getDFPath()
local fortName = dfhack.TranslateName(df.world_site.find(df.global.ui.site_id).name)
local savePath = dfhack.getSavePath()
local fileName = fortName .. ".json.dat"
local file_cur = gamePath .. "/data/save/current/" .. fileName
local file_sav = savePath .. "/" .. fileName
local cur = json.open(file_cur)
local saved = json.open(file_sav)
if saved.exists == true and cur.exists == false then
print("Previous session save data found. [" .. file_sav .. "]")
cur.data = saved.data
elseif saved.exists == false then
print("No session data found. All dwarves will be treated as non-optimized.")
--saved:write()
elseif cur.exists == true then
print("Existing session data found. [" .. file_cur .. "]")
end
OpData = cur.data
end
function SavePersistentData()
local gamePath = dfhack.getDFPath()
local fortName = dfhack.TranslateName(df.world_site.find(df.global.ui.site_id).name)
local fileName = fortName .. ".json.dat"
local cur = json.open(gamePath .. "/data/save/current/" .. fileName)
local newDwfTable = {}
for k,v in pairs(OpData.Dwarves) do
if v~=nil then
newDwfTable[k] = v
end
end
OpData.Dwarves = newDwfTable
cur.data = OpData
cur:write()
end
function ClearPersistentData(all)
local gamePath = dfhack.getDFPath()
local fortName = dfhack.TranslateName(df.world_site.find(df.global.ui.site_id).name)
local savePath = dfhack.getSavePath()
local fileName = fortName .. ".json.dat"
local file_cur = gamePath .. "/data/save/current/" .. fileName
local file_sav = savePath .. "/" .. fileName
local cur = json.open(gamePath .. "/data/save/current/" .. fileName)
print("Deleting " .. file_cur)
cur.data = {}
cur:write() --can't seem to find a way to fully nuke this file, unless manually done
if all then
print("Deleting " .. file_sav)
os.remove(file_sav)
end
end
function safecompare(a,b)
if a == b then
return 0
elseif tonumber(a) and tonumber(b) then
if a < b then
return -1
elseif a > b then
return 1
end
elseif tonumber(a) then
return 1
else
return -1
end
end
function twofield_compare(t,v1,v2,f1,f2,cmp1,cmp2)
local a = t[v1]
local b = t[v2]
local c1 = cmp1(a[f1],b[f1])
local c2 = cmp2(a[f2],b[f2])
if c1 == 0 then
return c2
end
return c1
end
--sorted pairs
function spairs(t, cmp)
-- collect the keys
local keys = {}
for k,v in pairs(t) do
table.insert(keys,k)
end
utils.sort_vector(keys, nil, cmp)
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
--random pairs
function rpairs(t, gen)
-- collect the keys
local keys = {}
for k,v in pairs(t) do
table.insert(keys,k)
end
-- return the iterator function
return function()
local i = gen:next()
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
function GetChar(str,i)
return string.sub(str,i,i)
end
function DisplayTable(t,recursion)
if recursion == nil then
print('###########################')
print(t)
print('######')
recursion = 0
elseif recursion == 1 then
print('-------------')
elseif recursion == 2 then
print('-------')
elseif recursion == 3 then
print('---')
end
for i,k in pairs(t) do
if type(k) ~= "table" then
print(i,k)
end
end
for i,k in pairs(t) do
if type(k) == "table" then
print(i,k)
DisplayTable(k,recursion+1)
if recursion >= 2 then
print('')
elseif recursion == 0 then
print('######')
end
end
end
if recursion == nil then
print('###########################')
end
end
function TableToString(t)
local s = '['
local n=0
for k,v in pairs(t) do
n=n+1
if n ~= 1 then
s = s .. ", "
end
s = s .. tostring(v)
end
s = s .. ']'
return s
end
function count_this(to_be_counted)
local count = -1
local var1 = ""
while var1 ~= nil do
count = count + 1
var1 = (to_be_counted[count])
end
count=count-1
return count
end
function ArrayLength(t)
local count = 0
for i,k in pairs(t) do
if tonumber(i) then
count = count + 1
end
end
return count
end
function TableLength(table) local count = 0 for i,k in pairs(table) do count = count + 1 end return
count end
function TableContainsValue(t,value)
for _,v in pairs(t) do
if v == value then
return true
end
end
return false
end
function FindValueKey(t, value, depth)
if depth == nil then
depth = 0
elseif depth == 10 then
return nil
end
for k,v in pairs(t) do
if v == value then
return k
elseif type(v) == 'table' then
if FindValueKey(v, value, depth + 1) ~= nil then
return k
end
end
end
return nil
end
function FindKeyValue(t, key)
for k,v in pairs(t) do
if k == key then
return v
end
end
end
function GetRandomTableEntry(gen, t)
-- iterate over whole table to get all keys
local keyset = {}
for k in pairs(t) do
table.insert(keyset, k)
end
-- now you can reliably return a random key
local N = TableLength(t)
local i = gen:next()
local key = keyset[i]
local R = t[key]
if args.debug and tonumber(args.debug) >= 3 then print(N,i,key,R) end
return R
end
local attrib_seq = rng.num_sequence:new(1,TableLength(cloned.attrib_levels))
function GetRandomAttribLevel() --returns a randomly generated value for assigning to an attribute
local gen = rng.crng:new(engineID,false,attrib_seq)
gen:shuffle()
while true do
local level = GetRandomTableEntry(gen, cloned.attrib_levels)
if rng.rollBool(engineID, level.p) then
return level
end
end
return nil
end
function isValidJob(job)
if job ~= nil and job.req ~= nil then
local jobName = FindValueKey(cloned.jobs, job)
local jd = cloned.distributions[jobName]
if not jd then
error(string.format("Job distribution not found. Job: %s; jobName: %s",job,jobName))
end
if OpData[jobName].count < jd.max then
return true
end
end
return false
end
--Gets the skill table for a skill id from a particular dwarf
function GetSkillTable(dwf, skill)
local id = df.job_skill[skill]
assert(id, "Invalid skill - GetSkillTable(" .. skill .. ")")
for _,skillTable in pairs(dwf.status.current_soul.skills) do
if skillTable.id == id then
return skillTable
end
end
if args.debug and tonumber(args.debug) >= 0 then print("Could not find skill: " .. skill) end
return nil
end
function GenerateStatValue(stat, atr_lvl)
atr_lvl = atr_lvl == nil and GetRandomAttribLevel() or cloned.attrib_levels[atr_lvl]
if args.debug and tonumber(args.debug) >= 4 then print(atr_lvl, atr_lvl[1], atr_lvl[2]) end
local R = rng.rollNormal(engineID, atr_lvl[1], atr_lvl[2])
local value = math.floor(R)
value = value < 0 and 0 or value
value = value > 5000 and 5000 or value
stat.value = stat.value < value and value or stat.value
if args.debug and tonumber(args.debug) >= 3 then print(R, stat.value) end
end
function LoopStatsTable(statsTable, callback)
for k, v in safe_pairs(statsTable) do
callback(v)
end
end
function ApplyType(dwf, dwf_type)
local type = cloned.types[dwf_type]
assert(type, "Invalid dwarf type.")
for attribute, atr_lvl in pairs(type.attribs) do
if args.debug and tonumber(args.debug) >= 3 then print(attribute, atr_lvl[1]) end
if
attribute == 'STRENGTH' or
attribute == 'AGILITY' or
attribute == 'TOUGHNESS' or
attribute == 'ENDURANCE' or
attribute == 'RECUPERATION' or
attribute == 'DISEASE_RESISTANCE'
then
GenerateStatValue(dwf.body.physical_attrs[attribute], atr_lvl[1])
elseif
attribute == 'ANALYTICAL_ABILITY' or
attribute == 'FOCUS' or
attribute == 'WILLPOWER' or
attribute == 'CREATIVITY' or
attribute == 'INTUITION' or
attribute == 'PATIENCE' or
attribute == 'MEMORY' or
attribute == 'LINGUISTIC_ABILITY' or
attribute == 'SPATIAL_SENSE' or
attribute == 'MUSICALITY' or
attribute == 'KINESTHETIC_SENSE' or
attribute == 'EMPATHY' or
attribute == 'SOCIAL_AWARENESS'
then
GenerateStatValue(dwf.status.current_soul.mental_attrs[attribute], atr_lvl[1])
else
error("Invalid stat:" .. attribute)
end
end
if type.skills ~= nil then
for skill, skillRange in pairs(type.skills) do
local sTable = GetSkillTable(dwf, skill)
if sTable == nil then
--print("ApplyType()", skill, skillRange)
utils.insert_or_update(dwf.status.current_soul.skills, { new = true, id = df.job_skill[skill], rating = 0 }, 'id')
sTable = GetSkillTable(dwf, skill)
end
local points = rng.rollInt(engineID, skillRange[1], skillRange[2])
sTable.rating = sTable.rating < points and points or sTable.rating
sTable.rating = sTable.rating > 20 and 20 or sTable.rating
sTable.rating = sTable.rating <= 1 and 1 or sTable.rating
if args.debug and tonumber(args.debug) >= 2 then print(skill .. ".rating = " .. sTable.rating) end
end
end
return true
end
--Apply only after previously validating
function ApplyProfession(dwf, profession, min, max)
local prof = cloned.professions[profession]
--todo: consider counting total dwarves trained in a profession [currently counting total sub-professions, of a job]
for skill, bonus in pairs(prof.skills) do
local sTable = GetSkillTable(dwf, skill)
if sTable == nil then
utils.insert_or_update(dwf.status.current_soul.skills, { new = true, id = df.job_skill[skill], rating = 0 }, 'id')
sTable = GetSkillTable(dwf, skill)
end
local points = rng.rollInt(engineID, min, max)
sTable.rating = sTable.rating < points and points or sTable.rating
--sTable.natural_skill_lvl =
sTable.rating = sTable.rating + bonus
sTable.rating = sTable.rating >= 20 and 20 or sTable.rating
sTable.rating = sTable.rating <= 2 and 2 or sTable.rating
if args.debug and tonumber(args.debug) >= 2 then print(skill .. ".rating = " .. sTable.rating) end
end
return true
end
--Apply only after previously validating
function ApplyJob(dwf, jobName) --job = dorf_jobs[X]
local jd = cloned.distributions[jobName]
local job = cloned.jobs[jobName]
if args.debug and tonumber(args.debug) >= 3 then print(dwf,job,jobName, OpData[jobName]) end
OpData[jobName].count = OpData[jobName].count + 1
jd.cur = OpData[jobName].count
local id = tostring(dwf.id)
DwarvesData[id] = {}
DwarvesData[id]['job'] = jobName
DwarvesData[id]['professions'] = {}
if not OpData[jobName] then
OpData[jobName] = {}
end
dwf.custom_profession = jobName
RollStats(dwf, job.types)
-- Apply required professions
local bAlreadySetProf2 = false
local job_req_sequence = rng.num_sequence:new()
for i=1,ArrayLength(job.req) do
job_req_sequence:add(i)
end
local gen = rng.crng:new(engineID,false,job_req_sequence)
--two required professions are set as the professional titles for a dwarf [prof1, prof2]
--so when more than 2 are required it is necessary to randomize the iteration of their application to a dwarf
--this is done with rpairs and the above RNG code
gen:shuffle()
job_req_sequence:add(0) --adding an out of bounds key (ie. 0) to ensure rpairs won't keep going forever
--[note it is added after shuffling]
local i = 0
for _, prof in pairs(job.req) do
--> Set Profession(s) (by #)
i = i + 1 --since the key can't tell us what iteration we're on
if i == 1 then
dwf.profession = df.profession[prof]
elseif i == 2 then
bAlreadySetProf2 = true
dwf.profession2 = df.profession[prof]
end
--These are required professions for this job class
ApplyProfession(dwf, prof, 11, 17)
end
-- Loop tertiary professions
-- Sort loop (asc)
local points = 11
local base_dec = 11 / job.max[1]
local total = 0
--We want to loop through professions according to need (ie. count & ratio(ie. p))
for prof, t in spairs(OpData[jobName].profs,
function(a,b)
return twofield_compare(OpData[jobName].profs,
a, b, 'count', 'p',
function(f1,f2) return safecompare(f1,f2) end,
function(f1,f2) return safecompare(f2,f1) end)
end)
do
if total < job.max[1] then
if args.debug and tonumber(args.debug) >= 1 then print("dwf id:", dwf.id, jobName, prof) end
local ratio = job[prof]
if ratio ~= nil then --[[not clear why this was happening, simple fix though
(tried to reproduce the next day and couldn't,
must have been a bad table lingering in memory between tests despite resetting persistent data and dwarves)
--]]
local max = math.ceil(points)
local min = math.ceil(points - 5)
min = min < 0 and 0 or min
--Firsts are special
if OpData[jobName].profs[prof].count < (ratio * OpData[jobName].count) and points > 7.7 then
ApplyProfession(dwf, prof, min, max)
table.insert(DwarvesData[id]['professions'], prof)
OpData[jobName].profs[prof].count = OpData[jobName].profs[prof].count + 1
if args.debug and tonumber(args.debug) >= 1 then print("count: ", OpData[jobName].profs[prof].count) end
if not bAlreadySetProf2 then
bAlreadySetProf2 = true
dwf.profession2 = df.profession[prof]
end
points = points - base_dec
total = total + 1
else
local p = OpData[jobName].profs[prof].count > 0 and (1 - (ratio / ((ratio*OpData[jobName].count) / OpData[jobName].profs[prof].count))) or ratio
p = p < 0 and 0 or p
p = p > 1 and 1 or p
--p = (p - math.floor(p)) >= 0.5 and math.ceil(p) or math.floor(p)
--> proc probability and check points
if points >= 1 and rng.rollBool(engineID, p) then
ApplyProfession(dwf, prof, min, max)
table.insert(DwarvesData[id]['professions'], prof)
OpData[jobName].profs[prof].count = OpData[jobName].profs[prof].count + 1
if args.debug and tonumber(args.debug) >= 1 then print("dwf id:", dwf.id, "count: ", OpData[jobName].profs[prof].count, jobName, prof) end
if not bAlreadySetProf2 then
bAlreadySetProf2 = true
dwf.profession2 = df.profession[prof]
end
points = points - base_dec
total = total + 1
end
end
end
end
end
if not bAlreadySetProf2 then
dwf.profession2 = dwf.profession
end
return true
end
function RollStats(dwf, types)
LoopStatsTable(dwf.body.physical_attrs, GenerateStatValue)
LoopStatsTable(dwf.status.current_soul.mental_attrs, GenerateStatValue)
for i, type in pairs(types) do
if args.debug and tonumber(args.debug) >= 4 then print(i, type) end
ApplyType(dwf, type)
end
for type, table in pairs(cloned.types) do
local p = table.p
if p ~= nil then
if rng.rollBool(engineID, p) then
ApplyType(dwf, type)
end
end
end
end
--Returns true if a job was found and applied, returns false otherwise
function FindJob(dwf, recursive)
if isDwarfOptimized(dwf) then
return false
end
for jobName, jd in spairs(cloned.distributions,
function(a,b)
return twofield_compare(cloned.distributions,
a, b, 'cur', 'max',
function(a,b) return safecompare(a,b) end,
function(a,b) return safecompare(b,a) end)
end)
do
if args.debug and tonumber(args.debug) >= 4 then print("FindJob() ", jobName) end
local job = cloned.jobs[jobName]
if isValidJob(job) then
if args.debug and tonumber(args.debug) >= 1 then print("Found a job!") end
ApplyJob(dwf, jobName)
return true
end
end
--not recursive => not recursively called (yet~)
if not recursive and TrySecondPassExpansion() then
return FindJob(dwf, true)
end
print(":WARNING: No job found, that is bad?!")
return false
end
function TrySecondPassExpansion() --Tries to expand distribution maximums
local curTotal = 0
for k,v in pairs(cloned.distributions) do
if v.cur ~= nil then
curTotal = curTotal + v.cur
end
end
if curTotal < work_force then
local I = 0
for i, v in pairs(cloned.distributions.Thresholds) do
if work_force >= v then
I = i + 1
end
end
local delta = 0
for jobName, jd in spairs(cloned.distributions,
function(a,b)
return twofield_compare(cloned.distributions,
a, b, 'max', 'cur',
function(a,b) return safecompare(a,b) end,
function(a,b) return safecompare(a,b) end)
end)
do
if cloned.jobs[jobName] then
if (curTotal + delta) < work_force then
delta = delta + jd[I]
jd.max = jd.max + jd[I]
end
end
end
return true
end
return false
end
function CleanDwarf(dwf)
threshold=tonumber(args.clean)
if threshold then
N=-1
for _,_ in ipairs(dwf.status.current_soul.skills) do
N = N + 1
end
utils.sort_vector(dwf.status.current_soul.skills, 'id')
for i=N,0,-1 do
v=dwf.status.current_soul.skills[i]
--print(i)
--print(v.rating,v.id,df.job_skill[v.id])
if v.rating <= threshold then
utils.erase_sorted_key(dwf.status.current_soul.skills, v.id, 'id')
end
end
return true
end
error("invalid value given for argument '-clean <value>'")
end
function ZeroDwarf(dwf)
LoopStatsTable(dwf.body.physical_attrs, function(attribute) attribute.value = 0 end)
LoopStatsTable(dwf.status.current_soul.mental_attrs, function(attribute) attribute.value = 0 end)
local count_max = count_this(df.job_skill)
utils.sort_vector(dwf.status.current_soul.skills, 'id')
for i=0, count_max do
utils.erase_sorted_key(dwf.status.current_soul.skills, i, 'id')
end
dfhack.units.setNickname(dwf, "")
dwf.custom_profession = ""
dwf.profession = df.profession['DRUNK']
dwf.profession2 = df.profession['DRUNK']
for id, dwf_data in pairs(DwarvesData) do
if next(dwf_data) ~= nil and id == tostring(dwf.id) then
print("Clearing loaded dwf data for dwf id: " .. id)
local jobName = dwf_data.job
local job = cloned.jobs[jobName]
OpData[jobName].count = OpData[jobName].count - 1
for i, prof in pairs(dwf_data.professions) do
OpData[jobName].profs[prof].count = OpData[jobName].profs[prof].count - 1
if args.debug and tonumber(args.debug) >= 1 then print("dwf id:", dwf.id, "count: ", OpData[jobName].profs[prof].count, jobName, prof) end
end
DwarvesData[id] = nil
--table.remove(DwarvesData,id)
elseif next(dwf_data) == nil and id == tostring(dwf.id) then
print(":WARNING: ZeroDwarf(dwf) - dwf was zeroed, but had never been optimized before")
--error("this dwf_data shouldn't be nil, I think.. I guess maybe if you were clearing dwarves that weren't optimized")
end
end
return true
end
function Reroll(dwf)
local id = tostring(dwf.id)
local jobName = DwarvesData[id].job
if cloned.jobs[jobName] then
if args.reroll ~= 'inclusive' then
ZeroDwarf(dwf)
end
ApplyJob(dwf, jobName)
return true
end
return false
end
function RenameJob(dwf)
if args.renamejob ~= nil then
dwf.custom_profession = args.renamejob
return true
end
return false
end
waves={}
local ticks_per_day = 1200;
local ticks_per_month = 28 * ticks_per_day;
local ticks_per_season = 3 * ticks_per_month;
local ticks_per_year = 12 * ticks_per_month;
local current_tick = df.global.cur_year_tick
local seasons = {
'spring',
'summer',
'autumn',
'winter',
}
function GetWave(dwf)
arrival_time = current_tick - dwf.curse.time_on_site;
--print(string.format("Current year %s, arrival_time = %s, ticks_per_year = %s", df.global.cur_year, arrival_time, ticks_per_year))
arrival_year = df.global.cur_year + (arrival_time // ticks_per_year);
arrival_season = 1 + (arrival_time % ticks_per_year) // ticks_per_season;
wave = 10 * arrival_year + arrival_season
if waves[wave] == nil then
waves[wave] = {}
end
table.insert(waves[wave],dwf)
--print(string.format("Arrived in the %s of the year %s. Wave %s, arrival time %s",seasons[season+1],year, wave, arrival_month))
end
function Show(dwf)
local name_ptr = dfhack.units.getVisibleName(dwf)
local name = dfhack.TranslateName(name_ptr)
print(string.format("%6d [wave:%2d] - %-23s (%3d,%3d) %s", dwf.id, tonumber(FindValueKey(zwaves,dwf)), name, dwf.profession, dwf.profession2, dwf.custom_profession))
--print('('..dwf.id..') - '..name..spaces..dwf.profession,dwf.custom_profession)
end
function LoopUnits(units, check, fn, checkoption, profmin, profmax) --cause nothing else will use arg 5 or 6
local count = 0
for _, unit in pairs(units) do
if check ~= nil then
if check(unit, checkoption, profmin, profmax) then
if fn ~= nil then
if fn(unit) then
count = count + 1
end
else
count = count + 1
end
end
elseif fn ~= nil then
if fn(unit) then
count = count + 1
end
end
end
if args.debug and tonumber(args.debug) >= 1 then
print("loop count: ", count)
end
return count
end
function LoopTable_Apply_ToUnits(units, apply, applytable, checktable, profmin, profmax) --cause nothing else will use arg 5 or 6
local count = 0
local temp = 0
for _,tvalue in pairs(applytable) do
if checktable[tvalue] then
temp = LoopUnits(units, apply, nil, tvalue, profmin, profmax)
count = count < temp and temp or count
else
error("\nInvalid option: " .. tvalue .. "\nLook-up table: " .. checktable)
end
end
return count
end
------------
--CHECKERS--
------------
--Returns true if the DWARF has a user-given name
function isDwarfNamed(dwf)
return dwf.status.current_soul.name.nickname ~= ""
end
--Returns true if the DWARF has a custom_profession
function isDwarfEmployed(dwf)
return dwf.custom_profession ~= ""
end
--Returns true if the DWARF is in the DwarvesData table
function isDwarfOptimized(dwf)
local id = tostring(dwf.id)
local dorf = DwarvesData[id]
return dorf ~= nil
end
--Returns true if the DWARF is not in the DwarvesData table
function isDwarfUnoptimized(dwf)
return (not isDwarfOptimized(dwf))
end
--Returns true if the DWARF uses a protection signal in its name or profession
function isDwarfProtected(dwf)
if dwf.custom_profession ~= "" then
for _,signal in pairs(protected_dwarf_signals) do
if string.find(dwf.custom_profession, signal, 1, true) then
return true
end
end
end
if dwf.status.current_soul.name.nickname ~= "" then
for _,signal in pairs(protected_dwarf_signals) do
if string.find(dwf.status.current_soul.name.nickname, signal, 1, true) then
return true
end
end
end
return false
end
--Returns true if the DWARF doesn't use a protection signal in its name or profession
function isDwarfUnprotected(dwf)
return (not isDwarfProtected(dwf))
end
function isDwarfCitizen(dwf)
return dfhack.units.isCitizen(dwf)
end
function CanWork(dwf)
return dfhack.units.isCitizen(dwf) and dfhack.units.isAdult(dwf)
end