forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventManager.cpp
More file actions
1483 lines (1338 loc) · 56.8 KB
/
EventManager.cpp
File metadata and controls
1483 lines (1338 loc) · 56.8 KB
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 "Debug.h"
#include "VTableInterpose.h"
#include "modules/Buildings.h"
#include "modules/Constructions.h"
#include "modules/EventManager.h"
#include "modules/Once.h"
#include "modules/Job.h"
#include "modules/Units.h"
#include "modules/World.h"
#include "df/announcement_type.h"
#include "df/building.h"
#include "df/construction.h"
#include "df/general_ref.h"
#include "df/general_ref_type.h"
#include "df/general_ref_unit_workerst.h"
#include "df/global_objects.h"
#include "df/historical_figure.h"
#include "df/interaction.h"
#include "df/item.h"
#include "df/item_actual.h"
#include "df/item_constructed.h"
#include "df/item_crafted.h"
#include "df/item_weaponst.h"
#include "df/job.h"
#include "df/job_list_link.h"
#include "df/report.h"
#include "df/plotinfost.h"
#include "df/unit.h"
#include "df/unit_flags1.h"
#include "df/unit_inventory_item.h"
#include "df/unit_report_type.h"
#include "df/unit_syndrome.h"
#include "df/unit_wound.h"
#include "df/world.h"
#include <algorithm>
#include <cstring>
#include <map>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <utility>
namespace DFHack {
DBG_DECLARE(eventmanager, log, DebugCategory::LINFO);
}
using namespace std;
using namespace DFHack;
using namespace EventManager;
using namespace df::enums;
/*
* TODO:
* error checking
* consider a typedef instead of a struct for EventHandler
**/
static multimap<int32_t, EventHandler> tickQueue;
//TODO: consider unordered_map of pairs, or unordered_map of unordered_set, or whatever
static multimap<Plugin*, EventHandler> handlers[EventType::EVENT_MAX];
static int32_t eventLastTick[EventType::EVENT_MAX];
static const int32_t ticksPerYear = 403200;
void DFHack::EventManager::registerListener(EventType::EventType e, EventHandler handler) {
DEBUG(log).print("registering handler %p from plugin %s for event %d\n", handler.eventHandler, !handler.plugin ? "<null>" : handler.plugin->getName().c_str(), e);
handlers[e].insert(pair<Plugin*, EventHandler>(handler.plugin, handler));
}
int32_t DFHack::EventManager::registerTick(EventHandler handler, int32_t when, bool absolute) {
if ( !absolute ) {
df::world* world = df::global::world;
if ( world ) {
when += world->frame_counter;
} else {
if ( Once::doOnce("EventManager registerTick unhonored absolute=false") )
Core::getInstance().getConsole().print("EventManager::registerTick: warning! absolute flag=false not honored.\n");
}
}
handler.freq = when;
tickQueue.insert(pair<int32_t, EventHandler>(handler.freq, handler));
DEBUG(log).print("registering handler %p from plugin %s for event TICK\n", handler.eventHandler, !handler.plugin ? "<null>" : handler.plugin->getName().c_str());
handlers[EventType::TICK].insert(pair<Plugin*,EventHandler>(handler.plugin,handler));
return when;
}
static void removeFromTickQueue(EventHandler getRidOf) {
for ( auto j = tickQueue.find(getRidOf.freq); j != tickQueue.end(); ) {
if ( (*j).first > getRidOf.freq )
break;
if ( (*j).second != getRidOf ) {
j++;
continue;
}
j = tickQueue.erase(j);
}
}
void DFHack::EventManager::unregister(EventType::EventType e, EventHandler handler) {
for ( auto i = handlers[e].find(handler.plugin); i != handlers[e].end(); ) {
if ( (*i).first != handler.plugin )
break;
EventHandler &handle = (*i).second;
if ( handle != handler ) {
i++;
continue;
}
DEBUG(log).print("unregistering handler %p from plugin %s for event %d\n", handler.eventHandler, !handler.plugin ? "<null>" : handler.plugin->getName().c_str(), e);
i = handlers[e].erase(i);
if ( e == EventType::TICK )
removeFromTickQueue(handler);
}
}
void DFHack::EventManager::unregisterAll(Plugin* plugin) {
DEBUG(log).print("unregistering all handlers for plugin %s\n", !plugin ? "<null>" : plugin->getName().c_str());
for ( auto i = handlers[EventType::TICK].find(plugin); i != handlers[EventType::TICK].end(); i++ ) {
if ( (*i).first != plugin )
break;
removeFromTickQueue((*i).second);
}
for (auto &handler : handlers) {
handler.erase(plugin);
}
}
static void manageTickEvent(color_ostream& out);
static void manageJobInitiatedEvent(color_ostream& out);
static void manageJobStartedEvent(color_ostream& out);
static void manageJobCompletedEvent(color_ostream& out);
static void manageNewUnitActiveEvent(color_ostream& out);
static void manageUnitDeathEvent(color_ostream& out);
static void manageItemCreationEvent(color_ostream& out);
static void manageBuildingEvent(color_ostream& out);
static void manageConstructionEvent(color_ostream& out);
static void manageSyndromeEvent(color_ostream& out);
static void manageInvasionEvent(color_ostream& out);
static void manageEquipmentEvent(color_ostream& out);
static void manageReportEvent(color_ostream& out);
static void manageUnitAttackEvent(color_ostream& out);
static void manageUnloadEvent(color_ostream& out){};
static void manageInteractionEvent(color_ostream& out);
typedef void (*eventManager_t)(color_ostream&);
// integrate new events into this function, and no longer worry about syncing the enum list with the `eventManager` array
eventManager_t getManager(EventType::EventType t) {
switch (t) {
case EventType::TICK:
return manageTickEvent;
case EventType::JOB_INITIATED:
return manageJobInitiatedEvent;
case EventType::JOB_STARTED:
return manageJobStartedEvent;
case EventType::JOB_COMPLETED:
return manageJobCompletedEvent;
case EventType::UNIT_NEW_ACTIVE:
return manageNewUnitActiveEvent;
case EventType::UNIT_DEATH:
return manageUnitDeathEvent;
case EventType::ITEM_CREATED:
return manageItemCreationEvent;
case EventType::BUILDING:
return manageBuildingEvent;
case EventType::CONSTRUCTION:
return manageConstructionEvent;
case EventType::SYNDROME:
return manageSyndromeEvent;
case EventType::INVASION:
return manageInvasionEvent;
case EventType::INVENTORY_CHANGE:
return manageEquipmentEvent;
case EventType::REPORT:
return manageReportEvent;
case EventType::UNIT_ATTACK:
return manageUnitAttackEvent;
case EventType::UNLOAD:
return manageUnloadEvent;
case EventType::INTERACTION:
return manageInteractionEvent;
case EventType::EVENT_MAX:
return nullptr;
//default:
//we don't do this... because then the compiler wouldn't error for missing cases in the enum
}
return nullptr;
}
std::array<eventManager_t,EventType::EVENT_MAX> compileManagerArray() {
std::array<eventManager_t, EventType::EVENT_MAX> managers{};
auto t = (EventType::EventType) 0;
while (t < EventType::EVENT_MAX) {
managers[t] = getManager(t);
t = (EventType::EventType) int(t + 1);
}
return managers;
}
//job initiated
static int32_t lastJobId = -1;
//job started
static std::vector<int32_t> startedJobs;
//job completed
struct JobCompleteData {
int32_t id;
int32_t completion_timer;
uint32_t flags_bits_repeat;
};
static std::unordered_map<int32_t, Job::JobUniquePtr> seenJobs;
static std::vector<JobCompleteData> prevJobs;
//active units
static unordered_set<int32_t> activeUnits;
//unit death
static unordered_set<int32_t> livingUnits;
//item creation
static int32_t nextItem;
//building
static int32_t nextBuilding;
static unordered_set<int32_t> buildings;
namespace std {
template <>
struct hash<df::construction> {
std::size_t operator()(const df::construction& construct) const {
return construct();
}
};
}
//construction
static unordered_set<df::construction> constructions;
static bool gameLoaded;
//syndrome
static int32_t lastSyndromeTime;
//invasion
static int32_t nextInvasion;
//equipment change
//static unordered_map<int32_t, vector<df::unit_inventory_item> > equipmentLog;
static unordered_map<int32_t, vector<InventoryItem>> equipmentLog;
//report
static int32_t lastReport;
//unit attack
static int32_t lastReportUnitAttack;
static std::map<int32_t,std::vector<int32_t>> reportToRelevantUnits;
static int32_t reportToRelevantUnitsTime = -1;
//interaction
static int32_t lastReportInteraction;
struct hash_pair {
template<typename A, typename B>
size_t operator()(const std::pair<A,B>& p) const {
auto h1 = std::hash<A>{}(p.first);
auto h2 = std::hash<B>{}(p.second);
return h1 ^ (h2 << 1);
}
};
static void run_handler(color_ostream& out, EventType::EventType eventType, const EventHandler & handle, void * arg) {
auto &core = Core::getInstance();
auto &counters = core.perf_counters;
uint32_t start_ms = core.p->getTickCount();
const char * plugin_name = !handle.plugin ? "<null>" : handle.plugin->getName().c_str();
handle.eventHandler(out, arg);
counters.incCounter(counters.event_manager_event_per_plugin_ms[eventType][plugin_name], start_ms);
}
void DFHack::EventManager::onStateChange(color_ostream& out, state_change_event event) {
static bool doOnce = false;
// const string eventNames[] = {"world loaded", "world unloaded", "map loaded", "map unloaded", "viewscreen changed", "core initialized", "begin unload", "paused", "unpaused"};
// out.print("%s,%d: onStateChange %d: \"%s\"\n", __FILE__, __LINE__, (int32_t)event, eventNames[event].c_str());
if ( !doOnce ) {
//TODO: put this somewhere else
doOnce = true;
EventHandler buildingHandler(nullptr, Buildings::updateBuildings, 100);
DFHack::EventManager::registerListener(EventType::BUILDING, buildingHandler);
//out.print("Registered listeners.\n %d", __LINE__);
}
if ( event == DFHack::SC_MAP_UNLOADED ) {
lastJobId = -1;
startedJobs.clear();
seenJobs.clear();
prevJobs.clear();
tickQueue.clear();
livingUnits.clear();
buildings.clear();
constructions.clear();
equipmentLog.clear();
activeUnits.clear();
Buildings::clearBuildings(out);
lastReport = -1;
lastReportUnitAttack = -1;
gameLoaded = false;
multimap<Plugin*,EventHandler> copy(handlers[EventType::UNLOAD].begin(), handlers[EventType::UNLOAD].end());
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for map unloaded state change event\n");
run_handler(out, EventType::UNLOAD, handle, nullptr);
}
} else if ( event == DFHack::SC_MAP_LOADED ) {
/*
int32_t tick = df::global::world->frame_counter;
multimap<int32_t,EventHandler> newTickQueue;
for ( auto i = tickQueue.begin(); i != tickQueue.end(); i++ )
newTickQueue.insert(pair<int32_t,EventHandler>(tick+(*i).first, (*i).second));
tickQueue.clear();
tickQueue.insert(newTickQueue.begin(), newTickQueue.end());
//out.print("%s,%d: on load, frame_counter = %d\n", __FILE__, __LINE__, tick);
*/
//tickQueue.clear();
if (!df::global::item_next_id)
return;
if (!df::global::building_next_id)
return;
if (!df::global::job_next_id)
return;
if (!df::global::plotinfo)
return;
if (!df::global::world)
return;
nextItem = *df::global::item_next_id;
nextBuilding = *df::global::building_next_id;
nextInvasion = df::global::plotinfo->invasions.next_id;
lastJobId = -1 + *df::global::job_next_id;
constructions.clear();
for (auto c : df::global::world->event.constructions) {
if ( !c ) {
if ( Once::doOnce("EventManager.onLoad null constr") ) {
out.print("EventManager.onLoad: null construction.\n");
}
continue;
}
if (c->pos == df::coord() ) {
if ( Once::doOnce("EventManager.onLoad null position of construction.\n") )
out.print("EventManager.onLoad null position of construction.\n");
continue;
}
constructions.emplace(*c);
}
for (auto b : df::global::world->buildings.all) {
Buildings::updateBuildings(out, (void*)intptr_t(b->id));
buildings.insert(b->id);
}
lastSyndromeTime = -1;
for (auto unit : df::global::world->units.all) {
if (Units::isActive(unit)) {
activeUnits.emplace(unit->id);
}
for (auto syndrome : unit->syndromes.active) {
int32_t startTime = syndrome->year*ticksPerYear + syndrome->year_time;
if ( startTime > lastSyndromeTime )
lastSyndromeTime = startTime;
}
}
lastReport = -1;
if ( !df::global::world->status.reports.empty() ) {
lastReport = df::global::world->status.reports[df::global::world->status.reports.size()-1]->id;
}
lastReportUnitAttack = -1;
lastReportInteraction = -1;
reportToRelevantUnitsTime = -1;
reportToRelevantUnits.clear();
for (int &last_tick : eventLastTick) {
last_tick = -1;//-1000000;
}
for (auto unit : df::global::world->history.figures) {
if ( unit->id < 0 && unit->name.language < 0 )
unit->name.language = 0;
}
gameLoaded = true;
}
}
void DFHack::EventManager::manageEvents(color_ostream& out) {
static const std::array<eventManager_t, EventType::EVENT_MAX> eventManager = compileManagerArray();
if ( !gameLoaded ) {
return;
}
if (!df::global::world)
return;
CoreSuspender suspender;
int32_t tick = df::global::world->frame_counter;
TRACE(log,out).print("processing events at tick %d\n", tick);
auto &core = Core::getInstance();
auto &counters = core.perf_counters;
for ( size_t a = 0; a < EventType::EVENT_MAX; a++ ) {
if ( handlers[a].empty() )
continue;
int32_t eventFrequency = -100;
if ( a != EventType::TICK )
for (auto &[_,handle] : handlers[a]) {
if (handle.freq < eventFrequency || eventFrequency == -100 )
eventFrequency = handle.freq;
}
else eventFrequency = 1;
if ( tick >= eventLastTick[a] && tick - eventLastTick[a] < eventFrequency )
continue;
uint32_t start_ms = core.p->getTickCount();
eventManager[a](out);
eventLastTick[a] = tick;
counters.incCounter(counters.event_manager_event_total_ms[a], start_ms);
}
}
static void manageTickEvent(color_ostream& out) {
if (!df::global::world)
return;
unordered_set<EventHandler> toRemove;
int32_t tick = df::global::world->frame_counter;
while ( !tickQueue.empty() ) {
if ( tick < (*tickQueue.begin()).first )
break;
EventHandler &handle = (*tickQueue.begin()).second;
tickQueue.erase(tickQueue.begin());
DEBUG(log,out).print("calling handler for tick event\n");
run_handler(out, EventType::TICK, handle, (void*)intptr_t(tick));
toRemove.insert(handle);
}
if ( toRemove.empty() )
return;
for ( auto a = handlers[EventType::TICK].begin(); a != handlers[EventType::TICK].end(); ) {
EventHandler &handle = (*a).second;
if ( toRemove.find(handle) == toRemove.end() ) {
a++;
continue;
}
a = handlers[EventType::TICK].erase(a);
toRemove.erase(handle);
if ( toRemove.empty() )
break;
}
}
static void manageJobInitiatedEvent(color_ostream& out) {
if (!df::global::world)
return;
if (!df::global::job_next_id)
return;
if ( lastJobId == -1 ) {
lastJobId = *df::global::job_next_id - 1;
return;
}
if ( lastJobId+1 == *df::global::job_next_id ) {
return; //no new jobs
}
multimap<Plugin*,EventHandler> copy(handlers[EventType::JOB_INITIATED].begin(), handlers[EventType::JOB_INITIATED].end());
for ( df::job_list_link* link = &df::global::world->jobs.list; link != nullptr; link = link->next ) {
if ( link->item == nullptr )
continue;
if ( link->item->id <= lastJobId )
continue;
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for job initiated event\n");
run_handler(out, EventType::JOB_INITIATED, handle, (void*)link->item);
}
}
lastJobId = *df::global::job_next_id - 1;
}
static void manageJobStartedEvent(color_ostream& out) {
if (!df::global::world)
return;
// iterate event handler callbacks
multimap<Plugin*, EventHandler> copy(handlers[EventType::JOB_STARTED].begin(), handlers[EventType::JOB_STARTED].end());
std::vector<int32_t> newStartedJobs;
newStartedJobs.reserve(startedJobs.size());
for (const auto jobPtr : df::global::world->jobs.list) {
// posting_index of -1 implies a worker has been assigned to a new job.
if (jobPtr->posting_index == -1) {
auto jobId = jobPtr->id;
newStartedJobs.push_back(jobId);
/*
* The startedJobs set peaks at the number of work-eligible citizens.
* This set is small enough to fit comfortably in the CPU caches,
* e.g., 200 workers * 4 bytes (jobId) = 800 bytes,
* ensuring better memory locality and thus more efficiency than a hashmap
* where memory access tends to be all over the place.
*/
if (!std::binary_search(startedJobs.begin(), startedJobs.end(), jobId)) {
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for job started event\n");
run_handler(out, EventType::JOB_STARTED, handle, jobPtr);
}
}
}
}
startedJobs = std::move(newStartedJobs);
}
/*
TODO: consider checking item creation / experience gain just in case
*/
static void manageJobCompletedEvent(color_ostream& out) {
if (!df::global::world)
return;
multimap<Plugin*, EventHandler> copy(handlers[EventType::JOB_COMPLETED].begin(), handlers[EventType::JOB_COMPLETED].end());
std::vector<JobCompleteData> nowJobs;
// predict the size in advance, this will prevent or reduce memory reallocation.
nowJobs.reserve(prevJobs.size());
for (const auto jobPtr : df::global::world->jobs.list) {
auto& job = *jobPtr;
auto seenIt = seenJobs.find(job.id);
if (seenIt != seenJobs.end()) {
/*
* No reference here, to prevent dangling reference situation
* when job is re-cloned.
*/
auto seenJob = seenIt->second.get();
// The key here is to strategically check the most important bits to reduce churn.
if (seenJob->flags.whole != job.flags.whole
|| (seenJob->items.size() != job.items.size())
|| (seenJob->general_refs.size() != job.general_refs.size())) {
seenIt->second = Job::JobUniquePtr(Job::cloneJobStruct(&job, true));
}
} else if (job.completion_timer != -1) {
// Restrict additions to seenJobs to jobs that we know have started.
seenJobs.emplace(job.id, Job::JobUniquePtr(Job::cloneJobStruct(&job, true)));
}
/*
* We still need to push back all jobs to maintain the invariant of the
* algorithm used with prevJobs and nowJobs.
*
* Consider a list of job IDs from the job list, including those
* that haven't started:
* 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
*
* We push back all jobs, including those that haven't started or have
* been assigned yet. Jobs that haven't started or finished have a
* completion_timer of -1.
*
* If we don't push back all jobs to the vector, we could encounter
* this situation:
*
* prevJob IDs (jobs with completion_timer != -1):
* 2, 4, 8, 10
*
* nowJobs IDs (completion_timer != -1 or had completion_timer != -1):
* 1, 2, 4, 8, 10
*
* In this case, Job with ID 1 has started after jobs 2, 4, 8, and 10.
* But, nowJobs is not greater than or equal to prevJobs because the ID
* 1 in nowJobs is less than the smallest ID in prevJobs,
* which breaks the algorithm.
*/
nowJobs.emplace_back(job.id, job.completion_timer, (bool)job.flags.bits.repeat);
}
// Do we want this check?
//assert(std::is_sorted(nowJobs.begin(), nowJobs.end()));
// uncomment if bay12 changes things to make job IDs not be in ascending order.
//std::ranges::sort(nowJobs, {}, &JobCompleteData::id);
#if 0
//testing info on job initiation/completion
//newly allocated jobs
for ( auto j = nowJobs.begin(); j != nowJobs.end(); j++ ) {
if ( prevJobs.find((*j).first) != prevJobs.end() )
continue;
df::job& job1 = *(*j).second;
out.print("new job\n"
" location : 0x%X\n"
" id : %d\n"
" type : %d %s\n"
" working : %d\n"
" completion_timer : %d\n"
" workerID : %d\n"
" time : %d -> %d\n"
"\n", job1.list_link->item, job1.id, job1.job_type, ENUM_ATTR(job_type, caption, job1.job_type), job1.flags.bits.working, job1.completion_timer, getWorkerID(&job1), tick0, tick1);
}
for ( auto i = prevJobs.begin(); i != prevJobs.end(); i++ ) {
df::job& job0 = *(*i).second;
auto j = nowJobs.find((*i).first);
if ( j == nowJobs.end() ) {
out.print("job deallocated\n"
" location : 0x%X\n"
" id : %d\n"
" type : %d %s\n"
" working : %d\n"
" completion_timer : %d\n"
" workerID : %d\n"
" time : %d -> %d\n"
,job0.list_link == NULL ? 0 : job0.list_link->item, job0.id, job0.job_type, ENUM_ATTR(job_type, caption, job0.job_type), job0.flags.bits.working, job0.completion_timer, getWorkerID(&job0), tick0, tick1);
continue;
}
df::job& job1 = *(*j).second;
if ( job0.flags.bits.working == job1.flags.bits.working &&
(job0.completion_timer == job1.completion_timer || (job1.completion_timer > 0 && job0.completion_timer-1 == job1.completion_timer)) &&
getWorkerID(&job0) == getWorkerID(&job1) )
continue;
out.print("job change\n"
" location : 0x%X -> 0x%X\n"
" id : %d -> %d\n"
" type : %d -> %d\n"
" type : %s -> %s\n"
" working : %d -> %d\n"
" completion timer : %d -> %d\n"
" workerID : %d -> %d\n"
" time : %d -> %d\n"
"\n",
job0.list_link->item, job1.list_link->item,
job0.id, job1.id,
job0.job_type, job1.job_type,
ENUM_ATTR(job_type, caption, job0.job_type), ENUM_ATTR(job_type, caption, job1.job_type),
job0.flags.bits.working, job1.flags.bits.working,
job0.completion_timer, job1.completion_timer,
getWorkerID(&job0), getWorkerID(&job1),
tick0, tick1
);
}
#endif
auto prevIt = prevJobs.begin();
auto nowIt = nowJobs.begin();
/*
* Iterate through two ordered sets, prevJobs and nowJobs, where job IDs in nowJobs are invariably
* greater than or equal to job IDs in prevJobs. The algorithm maintains the invariant that for each
* iteration nowIt is within valid range (not equal to nowJobs.end()), and prevIt->id is less than
* or equal to nowIt->id. Entries in nowJobs that are not found in prevJobs have IDs greater
* than any in prevJobs.
*/
while (prevIt != prevJobs.end()) {
auto& prevJob = *prevIt;
if (nowIt == nowJobs.end() || prevJob.id != nowIt->id) { // job ID is in prevJobs. ID does not exist in nowJobs.
// recently finished or cancelled job
if (!prevJob.flags_bits_repeat && prevJob.completion_timer == 0) {
// It should be in seenJobs.
auto seenIt = seenJobs.find(prevJob.id);
if (seenIt != seenJobs.end()) {
df::job& seenJob = *seenIt->second;
for (auto& [_, handle] : copy) {
DEBUG(log, out).print("calling handler for job completed event\n");
run_handler(out, EventType::JOB_COMPLETED, handle, (void*)&seenJob);
}
seenJobs.erase(prevJob.id);
}
}
} else { // prevIt job ID and nowIt job ID are equal.
// could have just finished if it's a repeat job
if (prevJob.flags_bits_repeat && prevJob.completion_timer == 0
&& nowIt->completion_timer == -1) {
// It should be in seenJobs.
auto seenIt = seenJobs.find(prevJob.id);
if (seenIt != seenJobs.end()) {
df::job& seenJob = *seenIt->second;
// still false positive if cancelled at EXACTLY the right time, but experiments show this doesn't happen
for (auto& [_, handle] : copy) {
DEBUG(log, out).print("calling handler for repeated job completed event\n");
run_handler(out, EventType::JOB_COMPLETED, handle, (void*)&seenJob);
}
}
}
// prevIt has caught up to nowIt.
++nowIt;
}
++prevIt;
}
/*
* Clean up garbage, if any.
* Jobs may be missed if tick delta > zero,
* and possibly other circumstances.
* To prevent leaking memory, we need to cleanup
* these missed jobs.
*/
if (seenJobs.size() > nowJobs.size() * 2) {
std::unordered_map<int32_t, Job::JobUniquePtr> newMap;
newMap.reserve(nowJobs.size());
for (auto& data : nowJobs) {
auto it = seenJobs.find(data.id);
if (it != seenJobs.end()) {
newMap.emplace(std::move(*it));
}
}
seenJobs.swap(newMap);
}
prevJobs = std::move(nowJobs);
}
static void manageNewUnitActiveEvent(color_ostream& out) {
if (!df::global::world)
return;
multimap<Plugin*,EventHandler> copy(handlers[EventType::UNIT_NEW_ACTIVE].begin(), handlers[EventType::UNIT_NEW_ACTIVE].end());
unordered_set<int32_t> next_activeUnits;
vector<int32_t> newly_active_unit_ids;
for (df::unit* unit : df::global::world->units.active) {
if (!Units::isActive(unit))
continue;
next_activeUnits.emplace(unit->id);
if (!activeUnits.count(unit->id))
newly_active_unit_ids.emplace_back(unit->id);
}
for (int32_t unit_id : newly_active_unit_ids) {
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for new unit event\n");
run_handler(out, EventType::UNIT_NEW_ACTIVE, handle, (void*) intptr_t(unit_id)); // intptr_t() avoids cast from smaller type warning
}
}
activeUnits = std::move(next_activeUnits);
}
static void manageUnitDeathEvent(color_ostream& out) {
if (!df::global::world)
return;
multimap<Plugin*,EventHandler> copy(handlers[EventType::UNIT_DEATH].begin(), handlers[EventType::UNIT_DEATH].end());
vector<int32_t> dead_unit_ids;
for (auto unit : df::global::world->units.all) {
//if ( unit->counters.death_id == -1 ) {
if ( Units::isActive(unit) ) {
livingUnits.insert(unit->id);
continue;
}
if (!Units::isDead(unit)) continue; // for units that have left the map but aren't dead
//dead: if dead since last check, trigger events
if ( livingUnits.find(unit->id) == livingUnits.end() )
continue;
livingUnits.erase(unit->id);
dead_unit_ids.emplace_back(unit->id);
}
for (int32_t unit_id : dead_unit_ids) {
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for unit death event\n");
run_handler(out, EventType::UNIT_DEATH, handle, (void*)intptr_t(unit_id));
}
}
}
static void manageItemCreationEvent(color_ostream& out) {
if (!df::global::world)
return;
if (!df::global::item_next_id)
return;
if ( nextItem >= *df::global::item_next_id ) {
return;
}
multimap<Plugin*,EventHandler> copy(handlers[EventType::ITEM_CREATED].begin(), handlers[EventType::ITEM_CREATED].end());
size_t index = df::item::binsearch_index(df::global::world->items.all, nextItem, false);
if ( index != 0 ) index--;
std::vector<int32_t> created_items;
for ( size_t a = index; a < df::global::world->items.all.size(); a++ ) {
df::item* item = df::global::world->items.all[a];
//already processed
if ( item->id < nextItem )
continue;
//invaders
if ( item->flags.bits.foreign )
continue;
//traders who bring back your items?
if ( item->flags.bits.trader )
continue;
//migrants
if ( item->flags.bits.owned )
continue;
//spider webs don't count
if ( item->flags.bits.spider_web )
continue;
created_items.push_back(item->id);
}
// handle all created items
for (int32_t item_id : created_items) {
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for item created event\n");
run_handler(out, EventType::ITEM_CREATED, handle, (void*)intptr_t(item_id));
}
}
nextItem = *df::global::item_next_id;
}
static void manageBuildingEvent(color_ostream& out) {
if (!df::global::world)
return;
if (!df::global::building_next_id)
return;
/*
* TODO: could be faster
* consider looking at jobs: building creation / destruction
**/
multimap<Plugin*,EventHandler> copy(handlers[EventType::BUILDING].begin(), handlers[EventType::BUILDING].end());
//first alert people about new buildings
vector<int32_t> new_buildings;
for ( int32_t a = nextBuilding; a < *df::global::building_next_id; a++ ) {
int32_t index = df::building::binsearch_index(df::global::world->buildings.all, a);
if ( index == -1 ) {
//out.print("%s, line %d: Couldn't find new building with id %d.\n", __FILE__, __LINE__, a);
//the tricky thing is that when the game first starts, it's ok to skip buildings, but otherwise, if you skip buildings, something is probably wrong. TODO: make this smarter
continue;
}
buildings.insert(a);
new_buildings.emplace_back(a);
}
nextBuilding = *df::global::building_next_id;
//now alert people about destroyed buildings
for ( auto it = buildings.begin(); it != buildings.end(); ) {
int32_t id = *it;
int32_t index = df::building::binsearch_index(df::global::world->buildings.all,id);
if ( index != -1 ) {
++it;
continue;
}
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for destroyed building event\n");
run_handler(out, EventType::BUILDING, handle, (void*)intptr_t(id));
}
it = buildings.erase(it);
}
//alert people about newly created buildings
std::for_each(new_buildings.begin(), new_buildings.end(), [&](int32_t building){
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for created building event\n");
run_handler(out, EventType::BUILDING, handle, (void*)intptr_t(building));
}
});
}
static void manageConstructionEvent(color_ostream& out) {
if (!df::global::world)
return;
//unordered_set<df::construction*> constructionsNow(df::global::world->event.constructions.begin(), df::global::world->event.constructions.end());
multimap<Plugin*, EventHandler> copy(handlers[EventType::CONSTRUCTION].begin(), handlers[EventType::CONSTRUCTION].end());
unordered_set<df::construction> next_construction_set; // will be swapped with constructions
next_construction_set.reserve(constructions.bucket_count());
vector<df::construction> new_constructions;
// find new constructions - swapping found constructions over from constructions to next_construction_set
for (auto c : df::global::world->event.constructions) {
auto &construction = *c;
auto it = constructions.find(construction);
if (it == constructions.end()) {
// handle new construction event later
new_constructions.emplace_back(construction);
}
else {
constructions.erase(it);
}
next_construction_set.emplace(construction);
}
constructions.swap(next_construction_set);
// now next_construction_set contains all the constructions that were removed (not found in df::global::world->event.constructions)
for (auto& construction : next_construction_set) {
// handle construction removed event
for (const auto &[_,handle]: copy) {
DEBUG(log,out).print("calling handler for destroyed construction event\n");
run_handler(out, EventType::CONSTRUCTION, handle, (void*) &construction);
}
}
// now handle all the new constructions
for (auto& construction : new_constructions) {
for (const auto &[_,handle]: copy) {
DEBUG(log,out).print("calling handler for created construction event\n");
run_handler(out, EventType::CONSTRUCTION, handle, (void*) &construction);
}
}
}
static void manageSyndromeEvent(color_ostream& out) {
if (!df::global::world)
return;
multimap<Plugin*,EventHandler> copy(handlers[EventType::SYNDROME].begin(), handlers[EventType::SYNDROME].end());
int32_t highestTime = -1;
std::vector<SyndromeData> new_syndrome_data;
for (auto unit : df::global::world->units.all) {
/*
if ( unit->flags1.bits.inactive )
continue;
*/
for ( size_t b = 0; b < unit->syndromes.active.size(); b++ ) {
df::unit_syndrome* syndrome = unit->syndromes.active[b];
int32_t startTime = syndrome->year*ticksPerYear + syndrome->year_time;
if ( startTime > highestTime )
highestTime = startTime;
if ( startTime <= lastSyndromeTime )
continue;
new_syndrome_data.emplace_back(unit->id, b);
}
}
for (auto& data : new_syndrome_data) {
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for syndrome event\n");
run_handler(out, EventType::SYNDROME, handle, (void*)&data);
}
}
lastSyndromeTime = highestTime;
}
static void manageInvasionEvent(color_ostream& out) {
if (!df::global::plotinfo)
return;
multimap<Plugin*,EventHandler> copy(handlers[EventType::INVASION].begin(), handlers[EventType::INVASION].end());
if ( df::global::plotinfo->invasions.next_id <= nextInvasion )
return;
nextInvasion = df::global::plotinfo->invasions.next_id;
for (auto &[_,handle] : copy) {
DEBUG(log,out).print("calling handler for invasion event\n");
run_handler(out, EventType::INVASION, handle, (void*)intptr_t(nextInvasion-1));
}
}
static void manageEquipmentEvent(color_ostream& out) {
if (!df::global::world)
return;
multimap<Plugin*,EventHandler> copy(handlers[EventType::INVENTORY_CHANGE].begin(), handlers[EventType::INVENTORY_CHANGE].end());
unordered_map<int32_t, InventoryItem> itemIdToInventoryItem;
unordered_set<int32_t> currentlyEquipped;
vector<InventoryChangeData> equipment_pickups;
vector<InventoryChangeData> equipment_drops;
vector<InventoryChangeData> equipment_changes;
// This vector stores the pointers to newly created changed items
// needed as the stack allocated temporary (in the loop) is lost when we go to
// handle the event calls, so we move that data to the heap if its needed,
// and then once we are done we delete everything.
vector<InventoryItem*> changed_items;
for (auto unit : df::global::world->units.all) {
itemIdToInventoryItem.clear();
currentlyEquipped.clear();
/*if ( unit->flags1.bits.inactive )
continue;
*/
auto oldEquipment = equipmentLog.find(unit->id);
bool hadEquipment = oldEquipment != equipmentLog.end();
vector<InventoryItem>* temp;
if ( hadEquipment ) {
temp = &((*oldEquipment).second);
} else {
temp = new vector<InventoryItem>;
}
//vector<InventoryItem>& v = (*oldEquipment).second;
vector<InventoryItem>& v = *temp;
for (auto & i : v) {
itemIdToInventoryItem[i.itemId] = i;
}