forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autolabor.cpp
1575 lines (1358 loc) · 52.4 KB
/
autolabor.cpp
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
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <PluginManager.h>
#include <vector>
#include <algorithm>
#include "modules/Units.h"
#include "modules/World.h"
// DF data structure definition headers
#include "DataDefs.h"
#include <df/ui.h>
#include <df/world.h>
#include <df/unit.h>
#include <df/unit_soul.h>
#include <df/unit_labor.h>
#include <df/unit_skill.h>
#include <df/job.h>
#include <df/building.h>
#include <df/workshop_type.h>
#include <df/unit_misc_trait.h>
#include <df/entity_position_responsibility.h>
#include <df/historical_figure.h>
#include <df/historical_entity.h>
#include <df/histfig_entity_link.h>
#include <df/histfig_entity_link_positionst.h>
#include <df/entity_position_assignment.h>
#include <df/entity_position.h>
#include <df/building_tradedepotst.h>
#include <df/building_stockpilest.h>
#include <df/items_other_id.h>
#include <df/ui.h>
#include <df/activity_info.h>
#include <MiscUtils.h>
#include "modules/MapCache.h"
#include "modules/Items.h"
#include "modules/Units.h"
using std::string;
using std::endl;
using std::vector;
using namespace DFHack;
using namespace df::enums;
DFHACK_PLUGIN("autolabor");
REQUIRE_GLOBAL(ui);
REQUIRE_GLOBAL(world);
#define ARRAY_COUNT(array) (sizeof(array)/sizeof((array)[0]))
/*
* Autolabor module for dfhack
*
* The idea behind this module is to constantly adjust labors so that the right dwarves
* are assigned to new tasks. The key is that, for almost all labors, once a dwarf begins
* a job it will finish that job even if the associated labor is removed. Thus the
* strategy is to frequently decide, for each labor, which dwarves should possibly take
* a new job for that labor if it comes in and which shouldn't, and then set the labors
* appropriately. The updating should happen as often as can be reasonably done without
* causing lag.
*
* The obvious thing to do is to just set each labor on a single idle dwarf who is best
* suited to doing new jobs of that labor. This works in a way, but it leads to a lot
* of idle dwarves since only one dwarf will be dispatched for each labor in an update
* cycle, and dwarves that finish tasks will wait for the next update before being
* dispatched. An improvement is to also set some labors on dwarves that are currently
* doing a job, so that they will immediately take a new job when they finish. The
* details of which dwarves should have labors set is mostly a heuristic.
*
* A complication to the above simple scheme is labors that have associated equipment.
* Enabling/disabling these labors causes dwarves to change equipment, and disabling
* them in the middle of a job may cause the job to be abandoned. Those labors
* (mining, hunting, and woodcutting) need to be handled carefully to minimize churn.
*/
DFHACK_PLUGIN_IS_ENABLED(enable_autolabor);
static bool print_debug = 0;
static std::vector<int> state_count(5);
static PersistentDataItem config;
enum ConfigFlags {
CF_ENABLED = 1,
};
// Here go all the command declarations...
// mostly to allow having the mandatory stuff on top of the file and commands on the bottom
command_result autolabor (color_ostream &out, std::vector <std::string> & parameters);
static void generate_labor_to_skill_map();
enum labor_mode {
DISABLE,
HAULERS,
AUTOMATIC,
};
enum dwarf_state {
// Ready for a new task
IDLE,
// Busy with a useful task
BUSY,
// Busy with a useful task that requires a tool
EXCLUSIVE,
// In the military, can't work
MILITARY,
// Child or noble, can't work
CHILD,
// Doing something that precludes working, may be busy for a while
OTHER
};
const int NUM_STATE = 6;
static const char *state_names[] = {
"IDLE",
"BUSY",
"EXCLUSIVE",
"MILITARY",
"CHILD",
"OTHER",
};
static const dwarf_state dwarf_states[] = {
BUSY /* CarveFortification */,
BUSY /* DetailWall */,
BUSY /* DetailFloor */,
EXCLUSIVE /* Dig */,
EXCLUSIVE /* CarveUpwardStaircase */,
EXCLUSIVE /* CarveDownwardStaircase */,
EXCLUSIVE /* CarveUpDownStaircase */,
EXCLUSIVE /* CarveRamp */,
EXCLUSIVE /* DigChannel */,
EXCLUSIVE /* FellTree */,
BUSY /* GatherPlants */,
BUSY /* RemoveConstruction */,
BUSY /* CollectWebs */,
BUSY /* BringItemToDepot */,
BUSY /* BringItemToShop */,
OTHER /* Eat */,
OTHER /* GetProvisions */,
OTHER /* Drink */,
OTHER /* Drink2 */,
OTHER /* FillWaterskin */,
OTHER /* FillWaterskin2 */,
OTHER /* Sleep */,
BUSY /* CollectSand */,
BUSY /* Fish */,
EXCLUSIVE /* Hunt */,
OTHER /* HuntVermin */,
BUSY /* Kidnap */,
BUSY /* BeatCriminal */,
BUSY /* StartingFistFight */,
BUSY /* CollectTaxes */,
BUSY /* GuardTaxCollector */,
BUSY /* CatchLiveLandAnimal */,
BUSY /* CatchLiveFish */,
BUSY /* ReturnKill */,
BUSY /* CheckChest */,
BUSY /* StoreOwnedItem */,
BUSY /* PlaceItemInTomb */,
BUSY /* StoreItemInStockpile */,
BUSY /* StoreItemInBag */,
BUSY /* StoreItemInHospital */,
BUSY /* StoreItemInChest */,
BUSY /* StoreItemInCabinet */,
BUSY /* StoreWeapon */,
BUSY /* StoreArmor */,
BUSY /* StoreItemInBarrel */,
BUSY /* StoreItemInBin */,
BUSY /* SeekArtifact */,
BUSY /* SeekInfant */,
OTHER /* AttendParty */,
OTHER /* GoShopping */,
OTHER /* GoShopping2 */,
BUSY /* Clean */,
OTHER /* Rest */,
EXCLUSIVE /* PickupEquipment */,
BUSY /* DumpItem */,
OTHER /* StrangeMoodCrafter */,
OTHER /* StrangeMoodJeweller */,
OTHER /* StrangeMoodForge */,
OTHER /* StrangeMoodMagmaForge */,
OTHER /* StrangeMoodBrooding */,
OTHER /* StrangeMoodFell */,
OTHER /* StrangeMoodCarpenter */,
OTHER /* StrangeMoodMason */,
OTHER /* StrangeMoodBowyer */,
OTHER /* StrangeMoodTanner */,
OTHER /* StrangeMoodWeaver */,
OTHER /* StrangeMoodGlassmaker */,
OTHER /* StrangeMoodMechanics */,
BUSY /* ConstructBuilding */,
BUSY /* ConstructDoor */,
BUSY /* ConstructFloodgate */,
BUSY /* ConstructBed */,
BUSY /* ConstructThrone */,
BUSY /* ConstructCoffin */,
BUSY /* ConstructTable */,
BUSY /* ConstructChest */,
BUSY /* ConstructBin */,
BUSY /* ConstructArmorStand */,
BUSY /* ConstructWeaponRack */,
BUSY /* ConstructCabinet */,
BUSY /* ConstructStatue */,
BUSY /* ConstructBlocks */,
BUSY /* MakeRawGlass */,
BUSY /* MakeCrafts */,
BUSY /* MintCoins */,
BUSY /* CutGems */,
BUSY /* CutGlass */,
BUSY /* EncrustWithGems */,
BUSY /* EncrustWithGlass */,
BUSY /* DestroyBuilding */,
BUSY /* SmeltOre */,
BUSY /* MeltMetalObject */,
BUSY /* ExtractMetalStrands */,
BUSY /* PlantSeeds */,
BUSY /* HarvestPlants */,
BUSY /* TrainHuntingAnimal */,
BUSY /* TrainWarAnimal */,
BUSY /* MakeWeapon */,
BUSY /* ForgeAnvil */,
BUSY /* ConstructCatapultParts */,
BUSY /* ConstructBallistaParts */,
BUSY /* MakeArmor */,
BUSY /* MakeHelm */,
BUSY /* MakePants */,
BUSY /* StudWith */,
BUSY /* ButcherAnimal */,
BUSY /* PrepareRawFish */,
BUSY /* MillPlants */,
BUSY /* BaitTrap */,
BUSY /* MilkCreature */,
BUSY /* MakeCheese */,
BUSY /* ProcessPlants */,
BUSY /* ProcessPlantsBag */,
BUSY /* ProcessPlantsVial */,
BUSY /* ProcessPlantsBarrel */,
BUSY /* PrepareMeal */,
BUSY /* WeaveCloth */,
BUSY /* MakeGloves */,
BUSY /* MakeShoes */,
BUSY /* MakeShield */,
BUSY /* MakeCage */,
BUSY /* MakeChain */,
BUSY /* MakeFlask */,
BUSY /* MakeGoblet */,
BUSY /* MakeInstrument */,
BUSY /* MakeToy */,
BUSY /* MakeAnimalTrap */,
BUSY /* MakeBarrel */,
BUSY /* MakeBucket */,
BUSY /* MakeWindow */,
BUSY /* MakeTotem */,
BUSY /* MakeAmmo */,
BUSY /* DecorateWith */,
BUSY /* MakeBackpack */,
BUSY /* MakeQuiver */,
BUSY /* MakeBallistaArrowHead */,
BUSY /* AssembleSiegeAmmo */,
BUSY /* LoadCatapult */,
BUSY /* LoadBallista */,
BUSY /* FireCatapult */,
BUSY /* FireBallista */,
BUSY /* ConstructMechanisms */,
BUSY /* MakeTrapComponent */,
BUSY /* LoadCageTrap */,
BUSY /* LoadStoneTrap */,
BUSY /* LoadWeaponTrap */,
BUSY /* CleanTrap */,
BUSY /* CastSpell */,
BUSY /* LinkBuildingToTrigger */,
BUSY /* PullLever */,
BUSY /* BrewDrink */,
BUSY /* ExtractFromPlants */,
BUSY /* ExtractFromRawFish */,
BUSY /* ExtractFromLandAnimal */,
BUSY /* TameVermin */,
BUSY /* TameAnimal */,
BUSY /* ChainAnimal */,
BUSY /* UnchainAnimal */,
BUSY /* UnchainPet */,
BUSY /* ReleaseLargeCreature */,
BUSY /* ReleasePet */,
BUSY /* ReleaseSmallCreature */,
BUSY /* HandleSmallCreature */,
BUSY /* HandleLargeCreature */,
BUSY /* CageLargeCreature */,
BUSY /* CageSmallCreature */,
BUSY /* RecoverWounded */,
BUSY /* DiagnosePatient */,
BUSY /* ImmobilizeBreak */,
BUSY /* DressWound */,
BUSY /* CleanPatient */,
BUSY /* Surgery */,
BUSY /* Suture */,
BUSY /* SetBone */,
BUSY /* PlaceInTraction */,
BUSY /* DrainAquarium */,
BUSY /* FillAquarium */,
BUSY /* FillPond */,
BUSY /* GiveWater */,
BUSY /* GiveFood */,
BUSY /* GiveWater2 */,
BUSY /* GiveFood2 */,
BUSY /* RecoverPet */,
BUSY /* PitLargeAnimal */,
BUSY /* PitSmallAnimal */,
BUSY /* SlaughterAnimal */,
BUSY /* MakeCharcoal */,
BUSY /* MakeAsh */,
BUSY /* MakeLye */,
BUSY /* MakePotashFromLye */,
BUSY /* FertilizeField */,
BUSY /* MakePotashFromAsh */,
BUSY /* DyeThread */,
BUSY /* DyeCloth */,
BUSY /* SewImage */,
BUSY /* MakePipeSection */,
BUSY /* OperatePump */,
OTHER /* ManageWorkOrders */,
OTHER /* UpdateStockpileRecords */,
OTHER /* TradeAtDepot */,
BUSY /* ConstructHatchCover */,
BUSY /* ConstructGrate */,
BUSY /* RemoveStairs */,
BUSY /* ConstructQuern */,
BUSY /* ConstructMillstone */,
BUSY /* ConstructSplint */,
BUSY /* ConstructCrutch */,
BUSY /* ConstructTractionBench */,
BUSY /* CleanSelf */,
BUSY /* BringCrutch */,
BUSY /* ApplyCast */,
BUSY /* CustomReaction */,
BUSY /* ConstructSlab */,
BUSY /* EngraveSlab */,
BUSY /* ShearCreature */,
BUSY /* SpinThread */,
BUSY /* PenLargeAnimal */,
BUSY /* PenSmallAnimal */,
BUSY /* MakeTool */,
BUSY /* CollectClay */,
BUSY /* InstallColonyInHive */,
BUSY /* CollectHiveProducts */,
OTHER /* CauseTrouble */,
OTHER /* DrinkBlood */,
OTHER /* ReportCrime */,
OTHER /* ExecuteCriminal */,
BUSY /* TrainAnimal */,
BUSY /* CarveTrack */,
BUSY /* PushTrackVehicle */,
BUSY /* PlaceTrackVehicle */,
BUSY /* StoreItemInVehicle */,
BUSY /* GeldAnimal */,
BUSY /* MakeFigurine */,
BUSY /* MakeAmulet */,
BUSY /* MakeScepter */,
BUSY /* MakeCrown */,
BUSY /* MakeRing */,
BUSY /* MakeEarring */,
BUSY /* MakeBracelet */,
BUSY /* MakeGem */
};
struct labor_info
{
PersistentDataItem config;
bool is_exclusive;
int active_dwarfs;
labor_mode mode() { return (labor_mode) config.ival(0); }
void set_mode(labor_mode mode) { config.ival(0) = mode; }
int minimum_dwarfs() { return config.ival(1); }
void set_minimum_dwarfs(int minimum_dwarfs) { config.ival(1) = minimum_dwarfs; }
int maximum_dwarfs() { return config.ival(2); }
void set_maximum_dwarfs(int maximum_dwarfs) { config.ival(2) = maximum_dwarfs; }
int talent_pool() { return config.ival(3); }
void set_talent_pool(int talent_pool) { config.ival(3) = talent_pool; }
};
struct labor_default
{
labor_mode mode;
bool is_exclusive;
int minimum_dwarfs;
int maximum_dwarfs;
int active_dwarfs;
};
// The percentage of the dwarves assigned as haulers at any one time.
static int hauler_pct = 33;
// The maximum percentage of dwarves who will be allowed to be idle.
// Decreasing this will encourage autolabor to keep dwarves busy,
// at the expense of making it harder for dwarves to specialize in
// specific skills.
static int idler_pct = 10;
static std::vector<struct labor_info> labor_infos;
static const struct labor_default default_labor_infos[] = {
/* MINE */ {AUTOMATIC, true, 2, 200, 0},
/* HAUL_STONE */ {HAULERS, false, 1, 200, 0},
/* HAUL_WOOD */ {HAULERS, false, 1, 200, 0},
/* HAUL_BODY */ {HAULERS, false, 1, 200, 0},
/* HAUL_FOOD */ {HAULERS, false, 1, 200, 0},
/* HAUL_REFUSE */ {HAULERS, false, 1, 200, 0},
/* HAUL_ITEM */ {HAULERS, false, 1, 200, 0},
/* HAUL_FURNITURE */ {HAULERS, false, 1, 200, 0},
/* HAUL_ANIMAL */ {HAULERS, false, 1, 200, 0},
/* CLEAN */ {HAULERS, false, 1, 200, 0},
/* CUTWOOD */ {AUTOMATIC, true, 1, 200, 0},
/* CARPENTER */ {AUTOMATIC, false, 1, 200, 0},
/* DETAIL */ {AUTOMATIC, false, 1, 200, 0},
/* MASON */ {AUTOMATIC, false, 1, 200, 0},
/* ARCHITECT */ {AUTOMATIC, false, 1, 200, 0},
/* ANIMALTRAIN */ {AUTOMATIC, false, 1, 200, 0},
/* ANIMALCARE */ {AUTOMATIC, false, 1, 200, 0},
/* DIAGNOSE */ {AUTOMATIC, false, 1, 200, 0},
/* SURGERY */ {AUTOMATIC, false, 1, 200, 0},
/* BONE_SETTING */ {AUTOMATIC, false, 1, 200, 0},
/* SUTURING */ {AUTOMATIC, false, 1, 200, 0},
/* DRESSING_WOUNDS */ {AUTOMATIC, false, 1, 200, 0},
/* FEED_WATER_CIVILIANS */ {AUTOMATIC, false, 200, 200, 0},
/* RECOVER_WOUNDED */ {HAULERS, false, 1, 200, 0},
/* BUTCHER */ {AUTOMATIC, false, 1, 200, 0},
/* TRAPPER */ {AUTOMATIC, false, 1, 200, 0},
/* DISSECT_VERMIN */ {AUTOMATIC, false, 1, 200, 0},
/* LEATHER */ {AUTOMATIC, false, 1, 200, 0},
/* TANNER */ {AUTOMATIC, false, 1, 200, 0},
/* BREWER */ {AUTOMATIC, false, 1, 200, 0},
/* ALCHEMIST */ {AUTOMATIC, false, 1, 200, 0},
/* SOAP_MAKER */ {AUTOMATIC, false, 1, 200, 0},
/* WEAVER */ {AUTOMATIC, false, 1, 200, 0},
/* CLOTHESMAKER */ {AUTOMATIC, false, 1, 200, 0},
/* MILLER */ {AUTOMATIC, false, 1, 200, 0},
/* PROCESS_PLANT */ {AUTOMATIC, false, 1, 200, 0},
/* MAKE_CHEESE */ {AUTOMATIC, false, 1, 200, 0},
/* MILK */ {AUTOMATIC, false, 1, 200, 0},
/* COOK */ {AUTOMATIC, false, 1, 200, 0},
/* PLANT */ {AUTOMATIC, false, 1, 200, 0},
/* HERBALIST */ {AUTOMATIC, false, 1, 200, 0},
/* FISH */ {AUTOMATIC, false, 1, 1, 0},
/* CLEAN_FISH */ {AUTOMATIC, false, 1, 200, 0},
/* DISSECT_FISH */ {AUTOMATIC, false, 1, 200, 0},
/* HUNT */ {AUTOMATIC, true, 1, 1, 0},
/* SMELT */ {AUTOMATIC, false, 1, 200, 0},
/* FORGE_WEAPON */ {AUTOMATIC, false, 1, 200, 0},
/* FORGE_ARMOR */ {AUTOMATIC, false, 1, 200, 0},
/* FORGE_FURNITURE */ {AUTOMATIC, false, 1, 200, 0},
/* METAL_CRAFT */ {AUTOMATIC, false, 1, 200, 0},
/* CUT_GEM */ {AUTOMATIC, false, 1, 200, 0},
/* ENCRUST_GEM */ {AUTOMATIC, false, 1, 200, 0},
/* WOOD_CRAFT */ {AUTOMATIC, false, 1, 200, 0},
/* STONE_CRAFT */ {AUTOMATIC, false, 1, 200, 0},
/* BONE_CARVE */ {AUTOMATIC, false, 1, 200, 0},
/* GLASSMAKER */ {AUTOMATIC, false, 1, 200, 0},
/* EXTRACT_STRAND */ {AUTOMATIC, false, 1, 200, 0},
/* SIEGECRAFT */ {AUTOMATIC, false, 1, 200, 0},
/* SIEGEOPERATE */ {AUTOMATIC, false, 1, 200, 0},
/* BOWYER */ {AUTOMATIC, false, 1, 200, 0},
/* MECHANIC */ {AUTOMATIC, false, 1, 200, 0},
/* POTASH_MAKING */ {AUTOMATIC, false, 1, 200, 0},
/* LYE_MAKING */ {AUTOMATIC, false, 1, 200, 0},
/* DYER */ {AUTOMATIC, false, 1, 200, 0},
/* BURN_WOOD */ {AUTOMATIC, false, 1, 200, 0},
/* OPERATE_PUMP */ {AUTOMATIC, false, 1, 200, 0},
/* SHEARER */ {AUTOMATIC, false, 1, 200, 0},
/* SPINNER */ {AUTOMATIC, false, 1, 200, 0},
/* POTTERY */ {AUTOMATIC, false, 1, 200, 0},
/* GLAZING */ {AUTOMATIC, false, 1, 200, 0},
/* PRESSING */ {AUTOMATIC, false, 1, 200, 0},
/* BEEKEEPING */ {AUTOMATIC, false, 1, 200, 0},
/* WAX_WORKING */ {AUTOMATIC, false, 1, 200, 0},
/* HANDLE_VEHICLES */ {HAULERS, false, 1, 200, 0},
/* HAUL_TRADE */ {HAULERS, false, 1, 200, 0},
/* PULL_LEVER */ {HAULERS, false, 1, 200, 0},
/* REMOVE_CONSTRUCTION */ {HAULERS, false, 1, 200, 0},
/* HAUL_WATER */ {HAULERS, false, 1, 200, 0},
/* GELD */ {AUTOMATIC, false, 1, 200, 0},
/* BUILD_ROAD */ {AUTOMATIC, false, 1, 200, 0},
/* BUILD_CONSTRUCTION */ {AUTOMATIC, false, 1, 200, 0},
/* PAPERMAKING */ {AUTOMATIC, false, 1, 200, 0},
/* BOOKBINDING */ {AUTOMATIC, false, 1, 200, 0}
};
static const int responsibility_penalties[] = {
0, /* LAW_MAKING */
0, /* LAW_ENFORCEMENT */
3000, /* RECEIVE_DIPLOMATS */
0, /* MEET_WORKERS */
1000, /* MANAGE_PRODUCTION */
3000, /* TRADE */
1000, /* ACCOUNTING */
0, /* ESTABLISH_COLONY_TRADE_AGREEMENTS */
0, /* MAKE_INTRODUCTIONS */
0, /* MAKE_PEACE_AGREEMENTS */
0, /* MAKE_TOPIC_AGREEMENTS */
0, /* COLLECT_TAXES */
0, /* ESCORT_TAX_COLLECTOR */
0, /* EXECUTIONS */
0, /* TAME_EXOTICS */
0, /* RELIGION */
0, /* ATTACK_ENEMIES */
0, /* PATROL_TERRITORY */
0, /* MILITARY_GOALS */
0, /* MILITARY_STRATEGY */
0, /* UPGRADE_SQUAD_EQUIPMENT */
0, /* EQUIPMENT_MANIFESTS */
0, /* SORT_AMMUNITION */
0, /* BUILD_MORALE */
5000 /* HEALTH_MANAGEMENT */
};
struct dwarf_info_t
{
int highest_skill;
int total_skill;
int mastery_penalty;
int assigned_jobs;
dwarf_state state;
bool has_exclusive_labor;
int noble_penalty; // penalty for assignment due to noble status
bool medical; // this dwarf has medical responsibility
bool trader; // this dwarf has trade responsibility
bool diplomacy; // this dwarf meets with diplomats
};
static bool isOptionEnabled(unsigned flag)
{
return config.isValid() && (config.ival(0) & flag) != 0;
}
static void setOptionEnabled(ConfigFlags flag, bool on)
{
if (!config.isValid())
return;
if (on)
config.ival(0) |= flag;
else
config.ival(0) &= ~flag;
}
static void cleanup_state()
{
enable_autolabor = false;
labor_infos.clear();
}
static void reset_labor(df::unit_labor labor)
{
labor_infos[labor].set_minimum_dwarfs(default_labor_infos[labor].minimum_dwarfs);
labor_infos[labor].set_maximum_dwarfs(default_labor_infos[labor].maximum_dwarfs);
labor_infos[labor].set_talent_pool(200);
labor_infos[labor].set_mode(default_labor_infos[labor].mode);
}
static void init_state()
{
config = World::GetPersistentData("autolabor/config");
if (config.isValid() && config.ival(0) == -1)
config.ival(0) = 0;
enable_autolabor = isOptionEnabled(CF_ENABLED);
if (!enable_autolabor)
return;
auto cfg_haulpct = World::GetPersistentData("autolabor/haulpct");
if (cfg_haulpct.isValid())
{
hauler_pct = cfg_haulpct.ival(0);
}
else
{
hauler_pct = 33;
}
// Load labors from save
labor_infos.resize(ARRAY_COUNT(default_labor_infos));
std::vector<PersistentDataItem> items;
World::GetPersistentData(&items, "autolabor/labors/", true);
for (auto p = items.begin(); p != items.end(); p++)
{
string key = p->key();
df::unit_labor labor = (df::unit_labor) atoi(key.substr(strlen("autolabor/labors/")).c_str());
if (labor >= 0 && labor <= labor_infos.size())
{
labor_infos[labor].config = *p;
labor_infos[labor].is_exclusive = default_labor_infos[labor].is_exclusive;
labor_infos[labor].active_dwarfs = 0;
}
}
// Add default labors for those not in save
for (int i = 0; i < ARRAY_COUNT(default_labor_infos); i++) {
if (labor_infos[i].config.isValid())
continue;
std::stringstream name;
name << "autolabor/labors/" << i;
labor_infos[i].config = World::AddPersistentData(name.str());
labor_infos[i].is_exclusive = default_labor_infos[i].is_exclusive;
labor_infos[i].active_dwarfs = 0;
reset_labor((df::unit_labor) i);
}
generate_labor_to_skill_map();
}
static df::job_skill labor_to_skill[ENUM_LAST_ITEM(unit_labor) + 1];
static void generate_labor_to_skill_map()
{
// Generate labor -> skill mapping
for (int i = 0; i <= ENUM_LAST_ITEM(unit_labor); i++)
labor_to_skill[i] = job_skill::NONE;
FOR_ENUM_ITEMS(job_skill, skill)
{
int labor = ENUM_ATTR(job_skill, labor, skill);
if (labor != unit_labor::NONE)
{
/*
assert(labor >= 0);
assert(labor < ARRAY_COUNT(labor_to_skill));
*/
labor_to_skill[labor] = skill;
}
}
}
static void enable_plugin(color_ostream &out)
{
if (!config.isValid())
{
config = World::AddPersistentData("autolabor/config");
config.ival(0) = 0;
}
setOptionEnabled(CF_ENABLED, true);
enable_autolabor = true;
out << "Enabling autolabor." << endl;
cleanup_state();
init_state();
}
DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands)
{
// initialize labor infos table from default table
if(ARRAY_COUNT(default_labor_infos) != ENUM_LAST_ITEM(unit_labor) + 1)
{
out.printerr("autolabor: labor size mismatch\n");
return CR_FAILURE;
}
// Fill the command list with your commands.
commands.push_back(PluginCommand(
"autolabor", "Automatically manage dwarf labors.",
autolabor, false, /* true means that the command can't be used from non-interactive user interface */
// Extended help string. Used by CR_WRONG_USAGE and the help command:
" autolabor enable\n"
" autolabor disable\n"
" Enables or disables the plugin.\n"
" autolabor <labor> <minimum> [<maximum>] [<talent pool>]\n"
" Set number of dwarves assigned to a labor.\n"
" autolabor <labor> haulers\n"
" Set a labor to be handled by hauler dwarves.\n"
" autolabor <labor> disable\n"
" Turn off autolabor for a specific labor.\n"
" autolabor <labor> reset\n"
" Return a labor to the default handling.\n"
" autolabor reset-all\n"
" Return all labors to the default handling.\n"
" autolabor list\n"
" List current status of all labors.\n"
" autolabor status\n"
" Show basic status information.\n"
"Function:\n"
" When enabled, autolabor periodically checks your dwarves and enables or\n"
" disables labors. It tries to keep as many dwarves as possible busy but\n"
" also tries to have dwarves specialize in specific skills.\n"
" Warning: autolabor will override any manual changes you make to labors\n"
" while it is enabled.\n"
" To prevent particular dwarves from being managed by autolabor, put them\n"
" in any burrow.\n"
" To restrict the assignment of a labor to only the top <n> most skilled\n"
" dwarves, add a talent pool number <n>.\n"
"Examples:\n"
" autolabor MINE 2\n"
" Keep at least 2 dwarves with mining enabled.\n"
" autolabor CUT_GEM 1 1\n"
" Keep exactly 1 dwarf with gemcutting enabled.\n"
" autolabor COOK 1 1 3\n"
" Keep 1 dwarf with cooking enabled, selected only from the top 3.\n"
" autolabor FEED_WATER_CIVILIANS haulers\n"
" Have haulers feed and water wounded dwarves.\n"
" autolabor CUTWOOD disable\n"
" Turn off autolabor for wood cutting.\n"
));
init_state();
return CR_OK;
}
DFhackCExport command_result plugin_shutdown ( color_ostream &out )
{
cleanup_state();
return CR_OK;
}
// sorting objects
struct dwarfinfo_sorter
{
dwarfinfo_sorter(std::vector <dwarf_info_t> & info):dwarf_info(info){};
bool operator() (int i,int j)
{
if (dwarf_info[i].state == IDLE && dwarf_info[j].state != IDLE)
return true;
if (dwarf_info[i].state != IDLE && dwarf_info[j].state == IDLE)
return false;
return dwarf_info[i].mastery_penalty > dwarf_info[j].mastery_penalty;
};
std::vector <dwarf_info_t> & dwarf_info;
};
struct laborinfo_sorter
{
bool operator() (int i,int j)
{
if (labor_infos[i].mode() != labor_infos[j].mode())
return labor_infos[i].mode() < labor_infos[j].mode();
if (labor_infos[i].is_exclusive != labor_infos[j].is_exclusive)
return labor_infos[i].is_exclusive;
if (labor_infos[i].maximum_dwarfs() != labor_infos[j].maximum_dwarfs())
return labor_infos[i].maximum_dwarfs() < labor_infos[j].maximum_dwarfs();
return false;
};
};
struct values_sorter
{
values_sorter(std::vector <int> & values):values(values){};
bool operator() (int i,int j)
{
return values[i] > values[j];
};
std::vector<int> & values;
};
static void assign_labor(unit_labor::unit_labor labor,
int n_dwarfs,
std::vector<dwarf_info_t>& dwarf_info,
bool trader_requested,
std::vector<df::unit *>& dwarfs,
bool has_butchers,
bool has_fishery,
color_ostream& out)
{
df::job_skill skill = labor_to_skill[labor];
if (labor_infos[labor].mode() != AUTOMATIC)
return;
int best_dwarf = 0;
int best_value = -10000;
int best_skill = 0;
std::vector<int> values(n_dwarfs);
std::vector<int> candidates;
std::map<int, int> dwarf_skill;
std::map<int, int> dwarf_skillxp;
std::vector<bool> previously_enabled(n_dwarfs);
auto mode = labor_infos[labor].mode();
// Find candidate dwarfs, and calculate a preference value for each dwarf
for (int dwarf = 0; dwarf < n_dwarfs; dwarf++)
{
if (dwarf_info[dwarf].state == CHILD)
continue;
if (dwarf_info[dwarf].state == MILITARY)
continue;
if (dwarf_info[dwarf].trader && trader_requested)
continue;
if (dwarf_info[dwarf].diplomacy)
continue;
if (labor_infos[labor].is_exclusive && dwarf_info[dwarf].has_exclusive_labor)
continue;
int value = dwarf_info[dwarf].mastery_penalty;
if (skill != job_skill::NONE)
{
int skill_level = 0;
int skill_experience = 0;
for (auto s = dwarfs[dwarf]->status.souls[0]->skills.begin(); s < dwarfs[dwarf]->status.souls[0]->skills.end(); s++)
{
if ((*s)->id == skill)
{
skill_level = (*s)->rating;
skill_experience = (*s)->experience;
break;
}
}
dwarf_skill[dwarf] = skill_level;
dwarf_skillxp[dwarf] = skill_experience;
if (best_skill < skill_level)
best_skill = skill_level;
value += skill_level * 100;
value += skill_experience / 20;
if (skill_level > 0 || skill_experience > 0)
value += 200;
if (skill_level >= 15)
value += 1000 * (skill_level - 14);
}
else
{
dwarf_skill[dwarf] = 0;
}
if (dwarfs[dwarf]->status.labors[labor])
{
value += 5;
if (labor_infos[labor].is_exclusive)
value += 350;
}
if (dwarf_info[dwarf].has_exclusive_labor)
value -= 500;
// bias by happiness
//value += dwarfs[dwarf]->status.happiness;
values[dwarf] = value;
candidates.push_back(dwarf);
}
int pool = labor_infos[labor].talent_pool();
if (pool < 200 && candidates.size() > 1 && abs(pool) < candidates.size())
{
// Sort in descending order
std::sort(candidates.begin(), candidates.end(), [&](const int lhs, const int rhs) -> bool {
if (dwarf_skill[lhs] == dwarf_skill[rhs])
if (pool > 0)
return dwarf_skillxp[lhs] > dwarf_skillxp[rhs];
else
return dwarf_skillxp[lhs] < dwarf_skillxp[rhs];
else
if (pool > 0)
return dwarf_skill[lhs] > dwarf_skill[rhs];
else
return dwarf_skill[lhs] < dwarf_skill[rhs];
});
// Check if all dwarves have equivalent skills, usually zero
int first_dwarf = candidates[0];
int last_dwarf = candidates[candidates.size() - 1];
if (dwarf_skill[first_dwarf] == dwarf_skill[last_dwarf] &&
dwarf_skillxp[first_dwarf] == dwarf_skillxp[last_dwarf])
{
// There's no difference in skill, so change nothing
}
else
{
// Trim down to our top (or not) talents
candidates.resize(abs(pool));
}
}
// Sort candidates by preference value
values_sorter ivs(values);
std::sort(candidates.begin(), candidates.end(), ivs);
// Disable the labor on everyone
for (int dwarf = 0; dwarf < n_dwarfs; dwarf++)
{
if (dwarf_info[dwarf].state == CHILD)
continue;
previously_enabled[dwarf] = dwarfs[dwarf]->status.labors[labor];
dwarfs[dwarf]->status.labors[labor] = false;
}
int min_dwarfs = labor_infos[labor].minimum_dwarfs();
int max_dwarfs = labor_infos[labor].maximum_dwarfs();
// Special - don't assign hunt without a butchers, or fish without a fishery
if (unit_labor::HUNT == labor && !has_butchers)
min_dwarfs = max_dwarfs = 0;
if (unit_labor::FISH == labor && !has_fishery)
min_dwarfs = max_dwarfs = 0;
// If there are enough idle dwarves to choose from, enter an aggressive assignment
// mode. "Enough" idle dwarves is defined as 2 or 10% of the total number of dwarves,
// whichever is higher.
//
// In aggressive mode, we will always pick at least one idle dwarf for each skill,
// in order to try to get the idle dwarves to start doing something. We also pick
// any dwarf more preferable to the idle dwarf, since we'd rather have a more
// preferable dwarf do a new job if one becomes available (probably because that
// dwarf just finished a job).
//
// In non-aggressive mode, only dwarves that are good at a labor will be assigned
// to it. Dwarves good at nothing, or nothing that needs doing, will tend to get
// assigned to hauling by the hauler code. If there are no hauling jobs to do,
// they will sit around idle and when enough build up they will trigger aggressive
// mode again.
bool aggressive_mode = state_count[IDLE] >= 2 && state_count[IDLE] >= n_dwarfs * idler_pct / 100;
/*
* Assign dwarfs to this labor. We assign at least the minimum number of dwarfs, in
* order of preference, and then assign additional dwarfs that meet any of these conditions:
* - We are in aggressive mode and have not yet assigned an idle dwarf
* - The dwarf is good at this skill
* - The labor is mining, hunting, or woodcutting and the dwarf currently has it enabled.
* We stop assigning dwarfs when we reach the maximum allowed.
* Note that only idle and busy dwarfs count towards the number of dwarfs. "Other" dwarfs
* (sleeping, eating, on break, etc.) will have labors assigned, but will not be counted.
* Military and children/nobles will not have labors assigned.
* Dwarfs with the "health management" responsibility are always assigned DIAGNOSIS.
*/
for (int i = 0; i < candidates.size() && labor_infos[labor].active_dwarfs < max_dwarfs; i++)
{
int dwarf = candidates[i];
if (dwarf_info[dwarf].trader && trader_requested)
continue;
if (dwarf_info[dwarf].diplomacy)
continue;
assert(dwarf >= 0);
assert(dwarf < n_dwarfs);
bool preferred_dwarf = false;
if (dwarf_skillxp[dwarf] > 0 && dwarf_skill[dwarf] >= best_skill / 2)
preferred_dwarf = true;
if (previously_enabled[dwarf] && labor_infos[labor].is_exclusive && dwarf_info[dwarf].state == EXCLUSIVE)
preferred_dwarf = true;
if (dwarf_info[dwarf].medical && labor == df::unit_labor::DIAGNOSE)
preferred_dwarf = true;
if (labor_infos[labor].active_dwarfs >= min_dwarfs && !preferred_dwarf && !aggressive_mode)
continue;
if (!dwarfs[dwarf]->status.labors[labor])
dwarf_info[dwarf].assigned_jobs++;
if (Units::isValidLabor(dwarfs[dwarf], labor))
dwarfs[dwarf]->status.labors[labor] = true;
if (labor_infos[labor].is_exclusive)
{
dwarf_info[dwarf].has_exclusive_labor = true;
// all the exclusive labors require equipment so this should force the dorf to reequip if needed
dwarfs[dwarf]->military.pickup_flags.bits.update = 1;
}
if (print_debug)
out.print("Dwarf %i \"%s\" assigned %s: value %i %s %s\n", dwarf, dwarfs[dwarf]->name.first_name.c_str(), ENUM_KEY_STR(unit_labor, labor).c_str(), values[dwarf], dwarf_info[dwarf].trader ? "(trader)" : "", dwarf_info[dwarf].diplomacy ? "(diplomacy)" : "");