forked from AirFoxTwo/FS25_FieldsOfStories
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIAGameLoopHelper.lua
More file actions
3705 lines (3474 loc) · 149 KB
/
Copy pathIAGameLoopHelper.lua
File metadata and controls
3705 lines (3474 loc) · 149 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
--
-- FS25 - InteractiveNeighbours - Game Loop Helper
--
-- @Interface: 1.0.0.0
-- @Author: AirFoxTwo
-- @Date: 23.01.2026
-- @Version: 1.0.0.0
-- Helper class for scenario generation logic
IAGameLoopHelper = {}
IAGameLoopHelper._mt = Class(IAGameLoopHelper)
-- Minimum distance (meters) from player to a place for a situation to be created there (avoids spawning when player is nearby)
IAGameLoopHelper.MIN_PLAYER_DISTANCE_FOR_PLACE_SITUATION = 20
-- Allowed crops for "next crop" selection (must match crops used in situations/fields_of_stories_situations.xml seed and fieldwork)
IAGameLoopHelper.NEXT_CROP_WHITELIST_NAMES = {
"CANOLA",
"WHEAT",
"BARLEY",
"OAT",
"SOYBEAN"
}
-- Daily fieldwork ordering (lower = earlier): harvest, seed, spray, fertilize subtypes, plow, harrow, cultivate — batch similar machines.
-- Keyed by IAFieldwork.JobType.* (canonical strings) so it tracks the enum without separate string drift.
IAGameLoopHelper.FIELDWORK_TYPE_PRIORITY = {
[IAFieldwork.JobType.HARVEST] = 1,
[IAFieldwork.JobType.SEED] = 2,
[IAFieldwork.JobType.SPRAY] = 3,
[IAFieldwork.JobType.MANURESPREADING] = 4,
[IAFieldwork.JobType.SLURRYSPREADING] = 4,
[IAFieldwork.JobType.FERTILIZEDSPREADING] = 4,
[IAFieldwork.JobType.PLOW] = 5,
[IAFieldwork.JobType.HARROW] = 6,
[IAFieldwork.JobType.CULTIVATE] = 7,
[IAFieldwork.JobType.IA_FIELD_OUTCOME] = 8,
}
-- Phone-accepted fieldwork uses IAFieldOutcomeMission only (no vanilla FertilizeMission / tryGenerateMission).
-- Inbound contract rings per schedule day: first at callPlayerHour:Minute, then at least +1 in-game hour from the previous actual ring.
IAGameLoopHelper.CONTRACT_CALL_MAX_RING_OPENS_PER_DAY = 3
IAGameLoopHelper.CONTRACT_CALL_RETRY_MIN_INGAME_MINUTES = 60
-- Maximum number of fields/farmlands a neighbour can outsource as contracts per day
IAGameLoopHelper.CONTRACT_MAX_FIELDS_PER_NEIGHBOUR_PER_DAY = 3
-- Create a new IAGameLoopHelper instance
-- @param table ianeighboursInstance - Reference to IANeighbours instance
function IAGameLoopHelper.new(ianeighboursInstance)
local self = setmetatable({}, IAGameLoopHelper._mt)
self.ianeighbours = ianeighboursInstance
self.homebaseParking = IAHomebaseParking.new(ianeighboursInstance)
return self
end
-- True if situation placetypes match runtime place.type or semantic basePlaceType (e.g. shop on player farm is type player_farm).
local function placeMatchesPlacetypes(place, placetypes)
if place == nil or placetypes == nil or #placetypes == 0 then
return false
end
if type(IAHelper_valueEqualsAnyInArrayIgnoreCase) == "function" and IAHelper_valueEqualsAnyInArrayIgnoreCase(place.type, placetypes) then
return true
end
local sem = (place.getSemanticType ~= nil and place:getSemanticType()) or place.type
if sem ~= nil and sem ~= place.type and type(IAHelper_valueEqualsAnyInArrayIgnoreCase) == "function" and IAHelper_valueEqualsAnyInArrayIgnoreCase(sem, placetypes) then
return true
end
return false
end
-- Place sizeType values that situations must explicitly opt into via <placeSizes>; never selected by default.
local IA_EXCLUSIVE_PLACE_SIZE_TYPES = {
["large_area"] = true,
}
--- True when the place's sizeType satisfies the situation config's <placeSizes> list.
-- - Empty/missing list: allow any size EXCEPT entries in IA_EXCLUSIVE_PLACE_SIZE_TYPES (opt-in only).
-- - Non-empty list: place.sizeType (case-insensitive) must equal one of the listed values.
local function placeMatchesRequestedSize(place, situationConfig)
if place == nil then
return false
end
local requested = situationConfig and situationConfig.placeSizes
local st = (place.sizeType ~= nil) and string.lower(tostring(place.sizeType)) or nil
if requested ~= nil and #requested > 0 then
if st == nil then
return false
end
if type(IAHelper_valueEqualsAnyInArrayIgnoreCase) == "function" then
return IAHelper_valueEqualsAnyInArrayIgnoreCase(st, requested) == true
end
for _, item in ipairs(requested) do
if string.lower(tostring(item)) == st then
return true
end
end
return false
end
if st ~= nil and IA_EXCLUSIVE_PLACE_SIZE_TYPES[st] == true then
return false
end
return true
end
--- Rebuild IAGameLoopHelper._placesByTypeBuckets when #places changed.
function IAGameLoopHelper:rebuildPlacesByTypeBucketsIfNeeded()
local places = self.ianeighbours and self.ianeighbours.places
if places == nil then
self._placesByTypeBuckets = nil
self._placesByTypeBucketsLen = nil
return
end
local n = #places
if self._placesByTypeBuckets ~= nil and self._placesByTypeBucketsLen == n then
return
end
local buckets = {}
for _, place in ipairs(places) do
if place ~= nil and place.type ~= nil then
local t1 = string.lower(tostring(place.type))
if buckets[t1] == nil then
buckets[t1] = {}
end
table.insert(buckets[t1], place)
local sem = (place.getSemanticType ~= nil and place:getSemanticType()) or nil
if sem ~= nil then
local t2 = string.lower(tostring(sem))
if t2 ~= t1 then
if buckets[t2] == nil then
buckets[t2] = {}
end
table.insert(buckets[t2], place)
end
end
end
end
self._placesByTypeBuckets = buckets
self._placesByTypeBucketsLen = n
end
function IAGameLoopHelper:invalidatePlacesTypeBucketCache()
self._placesByTypeBuckets = nil
self._placesByTypeBucketsLen = nil
end
--- Union of places that might match placetypes (type / semantic buckets), deduped; each entry verified with placeMatchesPlacetypes.
function IAGameLoopHelper:collectPlacesMatchingPlacetypes(placetypes)
self:rebuildPlacesByTypeBucketsIfNeeded()
local buckets = self._placesByTypeBuckets
if buckets == nil or placetypes == nil then
return {}
end
local seen = {}
local out = {}
for _, pt in ipairs(placetypes) do
local k = string.lower(tostring(pt))
for _, place in ipairs(buckets[k] or {}) do
if not seen[place] and placeMatchesPlacetypes(place, placetypes) then
seen[place] = true
table.insert(out, place)
end
end
end
return out
end
--- Priority rank for sorting fieldwork (unknown types last).
-- @param string|nil fieldworkLower - lowercase job string from config.fieldwork
-- @return number
function IAGameLoopHelper.getFieldworkPriorityRank(fieldworkLower)
if fieldworkLower == nil or fieldworkLower == "" then
return 999
end
local p = IAGameLoopHelper.FIELDWORK_TYPE_PRIORITY[fieldworkLower]
if p ~= nil then
return p
end
if IAFieldwork ~= nil and type(IAFieldwork.normalizeFieldworkJobType) == "function" then
local jt = IAFieldwork.normalizeFieldworkJobType(fieldworkLower)
if jt ~= nil then
local pj = IAGameLoopHelper.FIELDWORK_TYPE_PRIORITY[jt]
if pj ~= nil then
return pj
end
end
end
return 998
end
local function configIdSortKey(config)
if config == nil or config.id == nil then
return "\255"
end
local n = tonumber(config.id)
if n ~= nil then
return string.format("%012d", n)
end
return tostring(config.id)
end
local function compareFieldworkScheduleTasks(a, b)
if a == nil or b == nil then
return false
end
local ja = (a.config and a.config.fieldwork) and string.lower(tostring(a.config.fieldwork)) or ""
local jb = (b.config and b.config.fieldwork) and string.lower(tostring(b.config.fieldwork)) or ""
local ra = IAGameLoopHelper.getFieldworkPriorityRank(ja)
local rb = IAGameLoopHelper.getFieldworkPriorityRank(jb)
if ra ~= rb then
return ra < rb
end
-- Field order is a per-neighbour, per-day random permutation (fieldOrderKey) instead of
-- ascending farmlandId, so neighbours don't always start at their lowest field id.
-- Falls back to farmlandId when no random key was assigned (e.g. legacy loaded rows).
local fa = a.fieldOrderKey or a.farmlandId or 0
local fb = b.fieldOrderKey or b.farmlandId or 0
if fa ~= fb then
return fa < fb
end
return configIdSortKey(a.config) < configIdSortKey(b.config)
end
-- True if the planned next crop may be sown in the current period (FruitType growthDataSeasonal.plantingAllowed),
-- or when that data is missing, if current month appears on any matching SEED situation (legacy XML months).
function IAGameLoopHelper:isSowingMonthForPlannedSeed(neighbour, farmlandId)
if neighbour == nil or farmlandId == nil or self.ianeighbours.situationConfigs == nil then
return false
end
local nextCrop = (neighbour.assignedFarmlandNextCrop ~= nil and neighbour.assignedFarmlandNextCrop[farmlandId] ~= nil)
and neighbour.assignedFarmlandNextCrop[farmlandId]
or self:getNextCropForField(neighbour, farmlandId)
if nextCrop == nil then
return false
end
local planting = iaIsFruitTypePlantingAllowedInPeriod(nextCrop)
if planting == true then
return true
end
if planting == false then
return false
end
local currentMonth = getEnvironmentMonth1to12()
if currentMonth == nil then
return false
end
for _, config in ipairs(self.ianeighbours.situationConfigs) do
if config ~= nil and config.type ~= nil and string.lower(tostring(config.type)) == "fieldwork"
and config.fieldwork ~= nil and string.lower(tostring(config.fieldwork)) == "seed" then
if self:doesSituationConfigMatchNeighbour(config, neighbour) then
local seedIdx = IAFieldwork.resolveFruitTypeNameOrIndex(config.seedFruitTypeIndex)
if seedIdx ~= nil and seedIdx == nextCrop and config.months ~= nil and #config.months > 0 then
for _, monthNum in ipairs(config.months) do
if currentMonth == (tonumber(monthNum) or monthNum) then
return true
end
end
end
end
end
end
return false
end
function IAGameLoopHelper:findSituationConfigById(situationId)
if situationId == nil or self.ianeighbours.situationConfigs == nil then
return nil
end
for _, config in ipairs(self.ianeighbours.situationConfigs) do
if config ~= nil and tostring(config.id) == tostring(situationId) then
return config
end
end
return nil
end
--- True when an IAFieldOutcomeMission (player phone contract) is currently bound to the given farmland and not yet finished.
--- Falls back to scanning g_missionManager.missions when farmland.field.currentMission has not been set yet
--- (e.g. mission registered but startMission deferred). Active situations the AI started do not count here.
-- @param number farmlandId
-- @return boolean
function IAGameLoopHelper:hasActivePlayerFieldOutcomeForFarmland(farmlandId)
if farmlandId == nil then
return false
end
farmlandId = tonumber(farmlandId)
if farmlandId == nil then
return false
end
if g_farmlandManager ~= nil and type(g_farmlandManager.getFarmlands) == "function" then
local farmlands = g_farmlandManager:getFarmlands()
if farmlands ~= nil then
for _, f in pairs(farmlands) do
if f ~= nil and tonumber(f.id) == farmlandId and f.field ~= nil then
local mission = f.field.currentMission
if mission ~= nil and mission.farmId ~= nil then
return true
end
end
end
end
end
if g_missionManager ~= nil and g_missionManager.missions ~= nil then
for _, m in pairs(g_missionManager.missions) do
if m ~= nil and m.iaFieldsOfStoriesMission == true then
local mFarmland = m.iaFieldFarmlandId
if mFarmland == nil and m.field ~= nil and type(m.field.getFarmlandId) == "function" then
mFarmland = m.field:getFarmlandId()
end
if mFarmland ~= nil and tonumber(mFarmland) == farmlandId then
if MissionStatus == nil or m.status == nil
or m.status == MissionStatus.RUNNING
or m.status == MissionStatus.PREPARING
or m.status == MissionStatus.CREATED then
return true
end
end
end
end
end
return false
end
-- Build ordered daily queue from open candidates; mutates neighbour fieldwork schedule fields.
function IAGameLoopHelper:rebuildDailyFieldworkSchedule(neighbour)
local year, month, dayIn = getEnvironmentYearMonthDayInPeriod()
neighbour.fieldworkScheduleYear = year
neighbour.fieldworkScheduleMonth = month
neighbour.fieldworkScheduleDayInPeriod = dayIn
neighbour.fieldworkScheduleTasks = {}
neighbour.contractCallTriggerFiredForScheduleKey = nil
neighbour.contractCallRingOpensCount = 0
neighbour.contractCallRingAnsweredToday = false
neighbour.contractFallbackToAiFiredForScheduleKey = nil
neighbour.contractCallLastRingScheduleKey = nil
neighbour.contractCallLastRingTotalMinutes = nil
if IATestRunner ~= nil and type(IATestRunner.onScheduleRebuildBegin) == "function" then
IATestRunner.onScheduleRebuildBegin(neighbour)
end
--- Normalized fieldwork key for daily planning (stubble_cultivation → harrow; sow → seed).
local function fieldworkKeyForOutsource(cfg)
local jt = (cfg ~= nil and cfg.fieldwork) and string.lower(tostring(cfg.fieldwork)) or ""
if jt == "" then
return ""
end
if jt == "harvest" then
return "harvest"
end
if IAFieldwork ~= nil and type(IAFieldwork.normalizeFieldworkJobType) == "function" then
local n = IAFieldwork.normalizeFieldworkJobType(jt)
if n ~= nil then
return n
end
end
return jt
end
local all = self:collectOpenFieldworkCandidates(neighbour)
if #all == 0 then
return
end
local byField = {}
for _, c in ipairs(all) do
local fid = c.farmlandId
if byField[fid] == nil then
byField[fid] = {}
end
table.insert(byField[fid], c)
end
local chosen = {}
for _, farmlandId in ipairs(neighbour.assignedFarmlands) do
local matches = byField[farmlandId]
if matches ~= nil and #matches > 0 then
local urgent = self:isSowingMonthForPlannedSeed(neighbour, farmlandId)
if urgent then
local bestByJob = {}
for _, c in ipairs(matches) do
local jt = fieldworkKeyForOutsource(c.config)
local prev = bestByJob[jt]
if prev == nil or configIdSortKey(c.config) < configIdSortKey(prev.config) then
bestByJob[jt] = c
end
end
for _, c in pairs(bestByJob) do
table.insert(chosen, c)
end
else
local best = nil
for _, c in ipairs(matches) do
local jt = (c.config and c.config.fieldwork) and string.lower(tostring(c.config.fieldwork)) or ""
local rank = IAGameLoopHelper.getFieldworkPriorityRank(jt)
if best == nil then
best = c
else
local bjt = string.lower(tostring(best.config.fieldwork))
local br = IAGameLoopHelper.getFieldworkPriorityRank(bjt)
if rank < br or (rank == br and configIdSortKey(c.config) < configIdSortKey(best.config)) then
best = c
end
end
end
if best ~= nil then
table.insert(chosen, best)
end
end
end
end
-- Randomize the order fields are worked so neighbours don't always start at their lowest field id.
-- Build a shuffled permutation of this neighbour's assigned farmlands (stable for the whole game day,
-- since rebuild only runs on day change) and assign each task its field's position in that permutation.
-- compareFieldworkScheduleTasks uses this fieldOrderKey instead of ascending farmlandId.
local fieldOrderKeyByFarmland = {}
do
local ids = {}
for _, fid in ipairs(neighbour.assignedFarmlands) do
table.insert(ids, fid)
end
for i = #ids, 2, -1 do
local j = math.random(1, i)
ids[i], ids[j] = ids[j], ids[i]
end
for rank, fid in ipairs(ids) do
fieldOrderKeyByFarmland[fid] = rank
end
end
for _, c in ipairs(chosen) do
c.fieldOrderKey = fieldOrderKeyByFarmland[c.farmlandId]
end
table.sort(chosen, compareFieldworkScheduleTasks)
-- One outsourced fieldwork type per day (random among types present); harvest is never outsourced.
-- Also exclude the job type the neighbour is currently performing in an active fieldwork
-- situation: offering contracts for the same job type would race with the implements that
-- the active AI run still needs (slurry tank, fertilizer spreader, ...).
local activeJobTypeKey = nil
if neighbour.activeSituation ~= nil and neighbour.activeSituation.jobType ~= nil then
local rawActive = string.lower(tostring(neighbour.activeSituation.jobType))
if IAFieldwork ~= nil and type(IAFieldwork.normalizeFieldworkJobType) == "function" then
local norm = IAFieldwork.normalizeFieldworkJobType(rawActive)
if norm ~= nil and norm ~= "" then
activeJobTypeKey = norm
end
end
if activeJobTypeKey == nil and rawActive ~= "" then
activeJobTypeKey = rawActive
end
end
local distinctNonHarvestTypes = {}
local seenType = {}
for _, c in ipairs(chosen) do
local key = fieldworkKeyForOutsource(c.config)
local skip = false
if key == "" or key == "harvest" then
skip = true
end
if activeJobTypeKey ~= nil and key == activeJobTypeKey then
skip = true
end
if not skip and not seenType[key] then
seenType[key] = true
table.insert(distinctNonHarvestTypes, key)
end
end
local outsourcedJobType = nil
if #distinctNonHarvestTypes > 0 then
outsourcedJobType = distinctNonHarvestTypes[math.random(1, #distinctNonHarvestTypes)]
end
if self.ianeighbours.debug and activeJobTypeKey ~= nil then
print("--- IAGameLoopHelper:rebuildDailyFieldworkSchedule() - excluded active jobType '" .. tostring(activeJobTypeKey) .. "' from outsource pool for " .. tostring(neighbour.name))
end
local function rowIsContractForOutsource(c)
local key = fieldworkKeyForOutsource(c.config)
if key == "harvest" then
return false
end
return outsourcedJobType ~= nil and key == outsourcedJobType
end
local aiFirst = {}
local contractTail = {}
for _, c in ipairs(chosen) do
if rowIsContractForOutsource(c) then
table.insert(contractTail, c)
else
table.insert(aiFirst, c)
end
end
local ordered = {}
for _, c in ipairs(aiFirst) do
table.insert(ordered, c)
end
for _, c in ipairs(contractTail) do
table.insert(ordered, c)
end
local contractFieldCount = 0
local maxContractFields = IAGameLoopHelper.CONTRACT_MAX_FIELDS_PER_NEIGHBOUR_PER_DAY
-- Read from player setting; -1 means unlimited (no cap).
if IASettings ~= nil and type(IASettings.getContractMaxFieldsPerNeighbour) == "function" then
local settingCap = IASettings.getContractMaxFieldsPerNeighbour()
if settingCap ~= nil then
maxContractFields = settingCap
end
end
for _, c in ipairs(ordered) do
local row = {
situationId = c.config.id,
farmlandId = c.farmlandId,
}
if c.nextCropFruitTypeIndex ~= nil then
row.seedFruitTypeIndex = c.nextCropFruitTypeIndex
end
if rowIsContractForOutsource(c) then
if maxContractFields < 0 or contractFieldCount < maxContractFields then
row.contractEnabled = true
contractFieldCount = contractFieldCount + 1
end
-- Remaining contract-eligible rows become plain AI work (no contractEnabled flag)
end
table.insert(neighbour.fieldworkScheduleTasks, row)
end
-- Daily random call window (hour 8..14 inclusive, minute 0..59). Set once per game day (rebuild only runs on day change via ensureDailyFieldworkSchedule).
neighbour.callPlayerHour = math.random(8, 14)
neighbour.callPlayerMinute = math.random(0, 59)
if IATestRunner ~= nil and type(IATestRunner.onScheduleRebuildEnd) == "function" then
IATestRunner.onScheduleRebuildEnd(neighbour, outsourcedJobType)
end
if self.ianeighbours.debug then
local contractCount = 0
for _, t in ipairs(neighbour.fieldworkScheduleTasks) do
if t.contractEnabled then contractCount = contractCount + 1 end
end
print("--- IAGameLoopHelper:rebuildDailyFieldworkSchedule() - "..tostring(neighbour.name).." y="..tostring(year).." m="..tostring(month).." d="..tostring(dayIn).." tasks="..tostring(#neighbour.fieldworkScheduleTasks).." outsourceType="..tostring(outsourcedJobType or "none").." contracts="..tostring(contractCount).." callAt="..string.format("%02d:%02d", neighbour.callPlayerHour, neighbour.callPlayerMinute))
end
end
--- Apply completed field state for every still-valid row on yesterday's schedule (day rollover, before rebuild).
--- Skips accepted contracts (active mission), already-worked fields, and stale rows via validateScheduleEntry.
function IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd(neighbour)
if neighbour == nil or neighbour.fieldworkScheduleTasks == nil or #neighbour.fieldworkScheduleTasks == 0 then
return
end
if IAFieldwork == nil or type(IAFieldwork.enqueueCompleteFieldworkFieldUpdate) ~= "function" then
return
end
if g_farmlandManager == nil or type(g_farmlandManager.getFarmlands) ~= "function" then
return
end
local completed = 0
local tasks = neighbour.fieldworkScheduleTasks
for _, row in ipairs(tasks) do
local ok, err = pcall(function()
-- Resolve the job type up front: harvest needs relaxed validation at day end (see below),
-- so we must know the job before calling validateScheduleEntry.
local rowConfig = self:findSituationConfigById(row ~= nil and row.situationId or nil)
if rowConfig == nil or rowConfig.fieldwork == nil or rowConfig.fieldwork == "" then
return
end
local jobType = nil
if type(IAFieldwork.normalizeFieldworkJobType) == "function" then
jobType = IAFieldwork.normalizeFieldworkJobType(string.lower(tostring(rowConfig.fieldwork)))
end
if jobType == nil then
return
end
-- The calendar already rolled over before this runs, so the engine applied a day of growth
-- and withering. A harvest-ready crop left unworked yesterday is now withered and no longer
-- matches the situation's harvest growth trigger; relax the field-state trigger check for
-- harvest so the withered crop is still cleared (harvested) here.
local validateOpts = (jobType == IAFieldwork.JobType.HARVEST) and { skipFieldStateTriggerMatch = true } or nil
local valid = self:validateScheduleEntry(neighbour, row, validateOpts)
if valid == nil then
return
end
local field = nil
local farmlands = g_farmlandManager:getFarmlands()
if farmlands ~= nil then
for _, f in pairs(farmlands) do
if f ~= nil and f.id == valid.farmlandId and f.field ~= nil then
field = f.field
break
end
end
end
if field == nil then
return
end
local seedFruitTypeIndex = valid.nextCropFruitTypeIndex
local fertilizeSprayTypeIndex = nil
if type(IAFieldwork.getFertilizeSprayTypeIndexForJobType) == "function" then
fertilizeSprayTypeIndex = IAFieldwork.getFertilizeSprayTypeIndexForJobType(jobType)
end
-- Day-end variant compensates for the elapsed day: seeded crops advance one growth stage
-- (they would have grown overnight). Harvest leaves the field in its harvested (cut) state
-- even when the crop withered overnight.
local enqueued = false
if type(IAFieldwork.enqueueCompleteFieldworkFieldUpdateForDayEnd) == "function" then
enqueued = IAFieldwork.enqueueCompleteFieldworkFieldUpdateForDayEnd(field, jobType, seedFruitTypeIndex, fertilizeSprayTypeIndex)
else
IAFieldwork.enqueueCompleteFieldworkFieldUpdate(field, jobType, seedFruitTypeIndex, fertilizeSprayTypeIndex)
enqueued = true
end
if enqueued then
completed = completed + 1
end
end)
if not ok and self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd() - row failed: " .. tostring(err))
end
end
if self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd() - " .. tostring(neighbour.name)
.. " completed " .. tostring(completed) .. " of " .. tostring(#tasks) .. " scheduled tasks at day end")
end
end
function IAGameLoopHelper:calendarDayMatchesStoredSchedule(neighbour)
if neighbour == nil then
return false
end
local y, m, d = getEnvironmentYearMonthDayInPeriod()
if y == nil or m == nil or d == nil then
return false
end
if neighbour.fieldworkScheduleYear == nil or neighbour.fieldworkScheduleMonth == nil or neighbour.fieldworkScheduleDayInPeriod == nil then
return false
end
return neighbour.fieldworkScheduleYear == y
and neighbour.fieldworkScheduleMonth == m
and neighbour.fieldworkScheduleDayInPeriod == d
end
function IAGameLoopHelper:ensureDailyFieldworkSchedule(neighbour)
if neighbour == nil then
return
end
if neighbour.fieldworkScheduleTasks == nil then
neighbour.fieldworkScheduleTasks = {}
end
if not self:calendarDayMatchesStoredSchedule(neighbour) then
self:autoCompleteScheduledFieldworkAtDayEnd(neighbour)
self:rebuildDailyFieldworkSchedule(neighbour)
end
if self:calendarDayMatchesStoredSchedule(neighbour)
and neighbour.fieldworkScheduleTasks ~= nil
and #neighbour.fieldworkScheduleTasks == 0 then
-- Rebuilding here would reset contract-call bookkeeping and pick a new random outsource type
-- for the same calendar day, causing a second ring with missions that were not in today's plan.
local dayKey = self:getFieldworkScheduleDayKey(neighbour)
if dayKey ~= nil and neighbour.contractCallTriggerFiredForScheduleKey == dayKey then
return
end
self:rebuildDailyFieldworkSchedule(neighbour)
end
end
-- How many contract inbound rings can still fit from callPlayerHour today (same minute each hour), capped at CONTRACT_CALL_MAX_RING_OPENS_PER_DAY.
function IAGameLoopHelper.getContractCallRingSlotsCountForCallHour(callPlayerHour)
local h = tonumber(callPlayerHour)
if h == nil or h < 0 or h > 23 then
return 0
end
return math.min(IAGameLoopHelper.CONTRACT_CALL_MAX_RING_OPENS_PER_DAY, math.max(0, 24 - h))
end
-- Up to three in-game hourly slots (call time, +1h, +2h same minute); answering locks the rest of the day. Plan lock key set on first successful ring (see ensureDailyFieldworkSchedule).
function IAGameLoopHelper:evaluateContractPlayerCallTrigger(neighbour)
if neighbour == nil or not neighbour.initialized then
return
end
if neighbour.job ~= "Farmer" or neighbour.role ~= "Neighbour" then
return
end
if IANeighbours ~= nil and type(IANeighbours.isPlayerInAnyConversation) == "function" and IANeighbours.isPlayerInAnyConversation() then
return
end
if g_currentMission == nil or g_currentMission.environment == nil then
return
end
self:ensureDailyFieldworkSchedule(neighbour)
if not self:calendarDayMatchesStoredSchedule(neighbour) then
return
end
if neighbour.callPlayerHour == nil or neighbour.callPlayerMinute == nil then
return
end
local tasks = neighbour.fieldworkScheduleTasks
if tasks == nil then
return
end
local hasContract = false
for _, row in ipairs(tasks) do
if row ~= nil and row.contractEnabled == true then
hasContract = true
break
end
end
if not hasContract then
return
end
local env = g_currentMission.environment
local curH = env.currentHour or 0
local curM = env.currentMinute or 0
local curTotal = curH * 60 + curM
if g_inGameMenu ~= nil and g_inGameMenu.isOpen == true then
return
end
local mi = g_currentMission.missionInfo
if mi == nil or mi.timeScale == nil or mi.timeScale >= 500 then
return
end
local scheduleKey = tostring(neighbour.fieldworkScheduleYear) .. "_" .. tostring(neighbour.fieldworkScheduleMonth) .. "_" .. tostring(neighbour.fieldworkScheduleDayInPeriod)
if neighbour.contractCallRingAnsweredToday == true then
return
end
local maxOpens = IAGameLoopHelper.getContractCallRingSlotsCountForCallHour(neighbour.callPlayerHour)
if maxOpens <= 0 then
return
end
local opens = tonumber(neighbour.contractCallRingOpensCount) or 0
if opens >= maxOpens then
return
end
if opens > 0 then
local lastRingTotal = tonumber(neighbour.contractCallLastRingTotalMinutes)
if neighbour.contractCallLastRingScheduleKey == scheduleKey and lastRingTotal ~= nil then
local retryMinMinutes = tonumber(IAGameLoopHelper.CONTRACT_CALL_RETRY_MIN_INGAME_MINUTES) or 60
if curTotal < lastRingTotal + retryMinMinutes then
return
end
end
end
local slotHour = neighbour.callPlayerHour + opens
if slotHour > 23 then
return
end
local slotTotal = slotHour * 60 + (neighbour.callPlayerMinute or 0)
if curTotal < slotTotal then
return
end
-- Classic mission offer mode: no phone call rings at all.
if IASettings ~= nil and type(IASettings.isMissionOfferModeClassic) == "function" then
if IASettings.isMissionOfferModeClassic() then
return
end
end
-- Global per-day cap (IASettings.contractCallsPerDay): blocks any further contract rings
-- across all neighbours today once the configured cap is reached. Per-neighbour retry slots
-- above still apply within that budget.
if IASettings ~= nil and type(IASettings.canTriggerContractCallNow) == "function" then
if not IASettings.canTriggerContractCallNow() then
return
end
end
if IANeighbours ~= nil and type(IANeighbours.isGlobalInboundPhoneCooldownActive) == "function" then
if IANeighbours.isGlobalInboundPhoneCooldownActive() then
return
end
end
local showedRing = neighbour:onContractCallTimeTriggered()
if showedRing then
neighbour.contractCallRingOpensCount = opens + 1
neighbour.contractCallLastRingScheduleKey = scheduleKey
neighbour.contractCallLastRingTotalMinutes = curTotal
if neighbour.contractCallTriggerFiredForScheduleKey ~= scheduleKey then
neighbour.contractCallTriggerFiredForScheduleKey = scheduleKey
end
if IASettings ~= nil and type(IASettings.recordContractCallTriggered) == "function" then
IASettings.recordContractCallTriggered()
end
elseif IATestRunner ~= nil and IATestRunner._testActive then
-- All guards passed (game time >= call window) but ring failed to show.
-- Emit diagnostic so we can tell why the trigger didn't produce a payload.
IATestRunner.emit("phone", "natural_ring_blocked", {
neighbour = neighbour.name,
reason = "onContractCallTimeTriggered returned false (all time/state guards passed)",
callHour = neighbour.callPlayerHour,
callMinute = neighbour.callPlayerMinute,
curHour = curH,
curMinute = curM,
opens = opens,
maxOpens = maxOpens,
hasActiveSituation = neighbour.activeSituation ~= nil,
})
end
end
-- @return string|nil schedule day key "year_month_dayInPeriod"
function IAGameLoopHelper:getFieldworkScheduleDayKey(neighbour)
if neighbour == nil or neighbour.fieldworkScheduleYear == nil or neighbour.fieldworkScheduleMonth == nil or neighbour.fieldworkScheduleDayInPeriod == nil then
return nil
end
return tostring(neighbour.fieldworkScheduleYear) .. "_" .. tostring(neighbour.fieldworkScheduleMonth) .. "_" .. tostring(neighbour.fieldworkScheduleDayInPeriod)
end
-- Player accepted the full bundled contract offer: keep all rows in the daily schedule
-- but mark every contract-enabled row as acceptedByPlayer=true (and clear contractEnabled).
-- The schedule list stays complete; AI work selection (selectNewFieldwork) skips
-- acceptedByPlayer rows, and applyAcceptedContractMissionEndToSchedule restores them to
-- AI work on cancel/fail or removes them on success.
function IAGameLoopHelper:markAllContractRowsAsAcceptedByPlayer(neighbour)
if neighbour == nil or neighbour.fieldworkScheduleTasks == nil then
return
end
for _, row in ipairs(neighbour.fieldworkScheduleTasks) do
if row ~= nil and row.contractEnabled == true then
row.acceptedByPlayer = true
row.contractEnabled = nil
end
end
end
-- Player accepted the first `takeCount` rows of a bundled contract offer.
-- Schedule rows matching openList[1..takeCount] by (situationId, farmlandId) are marked
-- acceptedByPlayer=true (and lose contractEnabled). Any remaining contract-enabled rows
-- are demoted to plain AI work (contractEnabled=nil). No row is removed from the
-- schedule: applyAcceptedContractMissionEndToSchedule later removes accepted rows on
-- success or clears acceptedByPlayer on cancel/fail. Identity matching avoids positional
-- drift when the offer list and the schedule iterate in different orders or when some
-- rows were pruned/blocked between call time and accept time.
-- @param IANeighbour neighbour
-- @param table openList contract offer list (each entry has .config.id and .farmlandId)
-- @param number takeCount how many of the first openList rows the player accepted
function IAGameLoopHelper:markAcceptedContractRowsAndDemoteRest(neighbour, openList, takeCount)
if neighbour == nil or neighbour.fieldworkScheduleTasks == nil then
return
end
if openList == nil or #openList == 0 or takeCount == nil or takeCount <= 0 then
return
end
local acceptedKeys = {}
local limit = math.min(takeCount, #openList)
for i = 1, limit do
local row = openList[i]
local sid = (row ~= nil and row.config ~= nil and row.config.id ~= nil) and tostring(row.config.id) or nil
local fid = (row ~= nil) and tonumber(row.farmlandId) or nil
if sid ~= nil and fid ~= nil then
acceptedKeys[sid .. "|" .. fid] = true
end
end
for _, row in ipairs(neighbour.fieldworkScheduleTasks) do
if row ~= nil and row.contractEnabled == true then
local sid = row.situationId ~= nil and tostring(row.situationId) or nil
local fid = tonumber(row.farmlandId)
if sid ~= nil and fid ~= nil and acceptedKeys[sid .. "|" .. fid] then
row.acceptedByPlayer = true
row.contractEnabled = nil
else
row.contractEnabled = nil
end
end
end
end
-- Resolve a finished player-accepted contract mission against its source schedule row.
-- SUCCESS: the work is done -> remove the row from the schedule.
-- FAILED/CANCELED/TIMED_OUT: the player gave the work back -> clear acceptedByPlayer so
-- the neighbour AI can pick it up again.
-- Matches the row by (situationId, farmlandId); silently returns when the row no longer
-- exists (e.g. day rolled over, mission survived across day-rebuild).
-- @param IANeighbour neighbour owning neighbour
-- @param string situationId schedule row situation id
-- @param number farmlandId schedule row farmland id
-- @param number missionFinishState MissionFinishState.SUCCESS / FAILED / CANCELED / TIMED_OUT
function IAGameLoopHelper:applyAcceptedContractMissionEndToSchedule(neighbour, situationId, farmlandId, missionFinishState)
if neighbour == nil or neighbour.fieldworkScheduleTasks == nil then
return
end
if situationId == nil or farmlandId == nil then
return
end
local sid = tostring(situationId)
local fid = tonumber(farmlandId)
if sid == "" or fid == nil then
return
end
local tasks = neighbour.fieldworkScheduleTasks
for i = 1, #tasks do
local row = tasks[i]
if row ~= nil
and row.acceptedByPlayer == true
and row.situationId ~= nil
and tostring(row.situationId) == sid
and tonumber(row.farmlandId) == fid
then
if MissionFinishState ~= nil and missionFinishState == MissionFinishState.SUCCESS then
table.remove(tasks, i)
if self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:applyAcceptedContractMissionEndToSchedule() - SUCCESS removed row sid=" .. sid .. " fid=" .. tostring(fid) .. " neighbour=" .. tostring(neighbour.name))
end
else
row.acceptedByPlayer = nil
if self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:applyAcceptedContractMissionEndToSchedule() - non-SUCCESS (" .. tostring(missionFinishState) .. ") restored row to AI work sid=" .. sid .. " fid=" .. tostring(fid) .. " neighbour=" .. tostring(neighbour.name))
end
end
return
end
end
end
local function iaResolveSeedFruitTypeIndex(openFieldwork)
if openFieldwork == nil then
return nil
end
local idx = openFieldwork.nextCropFruitTypeIndex
if idx ~= nil then
return idx
end
-- If the situation config explicitly names a seed fruit type, prefer that.
local cfg = openFieldwork.config
if cfg ~= nil and cfg.seedFruitTypeIndex ~= nil and cfg.seedFruitTypeIndex ~= "" then
local resolved = IAFieldwork.resolveFruitTypeNameOrIndex(cfg.seedFruitTypeIndex)
if resolved ~= nil then
return resolved
end
end
-- Fallback: pick any seeding-enabled fruit type that is marked for field missions.
if g_fruitTypeManager ~= nil and g_fruitTypeManager.getFruitTypes ~= nil then
for _, ft in ipairs(g_fruitTypeManager:getFruitTypes()) do
if ft ~= nil and ft.index ~= nil and ft.useForFieldMissions and ft.allowsSeeding then
return ft.index
end
end
end
return nil
end
--- Build expected FieldState keys for IAFieldOutcomeMission (phone contracts).
-- Base from IAFieldwork.getExpectedFieldStateAfterJob (seed + fertilize spray from config), then situation fieldStateOutcome; fertilize sprayType from tools wins over XML.
function IAGameLoopHelper:buildPhoneFieldStateOutcome(openFieldwork, field)
local config = openFieldwork.config
local out = {}
local jobStr = (config ~= nil and config.fieldwork ~= nil and config.fieldwork ~= "") and string.lower(tostring(config.fieldwork)) or ""
local jobEnum = (IAFieldwork ~= nil and IAFieldwork.normalizeFieldworkJobType ~= nil) and IAFieldwork.normalizeFieldworkJobType(jobStr) or nil
local seedIdx = nil
if jobEnum == IAFieldwork.JobType.SEED then
seedIdx = iaResolveSeedFruitTypeIndex(openFieldwork)
if seedIdx ~= nil then
openFieldwork.nextCropFruitTypeIndex = seedIdx
end
end
local fertSpray = nil
if IAFieldwork ~= nil and IAFieldwork.isFertilizeJobType(jobEnum) and type(IAFieldwork.getFertilizeSprayTypeIndexForJobType) == "function" then
fertSpray = IAFieldwork.getFertilizeSprayTypeIndexForJobType(jobEnum)
end
if IAFieldwork ~= nil and IAFieldwork.getExpectedFieldStateAfterJob ~= nil and jobEnum ~= nil and field ~= nil then
local base = IAFieldwork.getExpectedFieldStateAfterJob(jobEnum, field, seedIdx, fertSpray)
for k, v in pairs(base) do
if type(k) == "string" and type(v) == "number" then
out[k] = v
end
end
end
if config ~= nil and config.fieldStateOutcome ~= nil then
for k, v in pairs(config.fieldStateOutcome) do
if type(k) == "string" and type(v) == "number" then
out[k] = v
end
end
end
if IAFieldwork.isFertilizeJobType(jobEnum) and fertSpray ~= nil then
out.sprayType = fertSpray
end
-- triggerFruitTypeIndex lists acceptable crops for *offering* the job, not a post-job outcome (spray/fertilize/etc. do not change crop).
if jobEnum == IAFieldwork.JobType.SEED and config ~= nil and config.triggerFruitTypeIndex ~= nil and config.triggerFruitTypeIndex[1] ~= nil and out.fruitTypeIndex == nil then
local idx = IAFieldwork.resolveFruitTypeNameOrIndex(config.triggerFruitTypeIndex[1])
if idx ~= nil then
out.fruitTypeIndex = idx