Repository navigation
Expand file tree
/
Copy pathIAHelper.lua
More file actions
3650 lines (3424 loc) · 125 KB
/
Copy pathIAHelper.lua
File metadata and controls
3650 lines (3424 loc) · 125 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
-- IAHelper.lua — library of global functions (IAHelper_* and other globals). Not a Class / not an IAHelper {} method table.
-- Neighbour PlaceableHotspot overlays (IANeighbours.registerNpcMapHotspotTexture): main map icon + small variant.
IA_NPC_MAP_OVERLAY_SLICE = IA_NPC_MAP_OVERLAY_SLICE or "iaFosNpc.npc"
IA_NPC_MAP_OVERLAY_SLICE_SMALL = IA_NPC_MAP_OVERLAY_SLICE_SMALL or "iaFosNpcSm.npc"
-- Borrow yard marker (IABorrowAccess.registerBorrowMapHotspotTexture): images/mapicon_borrow.dds
IA_BORROW_MAP_OVERLAY_SLICE = IA_BORROW_MAP_OVERLAY_SLICE or "iaFosBorrow.borrow"
--- @return boolean true if hotspot was registered with the mission/HUD
function iaAddMapHotspotToMission(hotspot)
if g_currentMission == nil or hotspot == nil then
IAprintDebug("iaAddMapHotspotToMission()", string.format(
"[HOTSPOT] ADD skipped (g_currentMission=%s hotspot=%s)",
tostring(g_currentMission ~= nil), tostring(hotspot ~= nil)
), nil, nil, nil)
return false
end
local label = tostring(hotspot.name ~= nil and hotspot:getName() or hotspot)
if g_currentMission.addMapHotspot ~= nil then
g_currentMission:addMapHotspot(hotspot)
IAprintDebug("iaAddMapHotspotToMission()", string.format(
"[HOTSPOT] ADD ok via g_currentMission:addMapHotspot name=%s isADMarker=%s neighbourMarker=%s yardMarker=%s yardPlaceKey=%s",
label, tostring(hotspot.isADMarker), tostring(hotspot.iaFosNeighbourMarker),
tostring(hotspot.iaFosBorrowYardMarker), tostring(hotspot.iaFosBorrowYardPlaceKey)
), nil, nil, nil)
return true
end
if g_currentMission.hud ~= nil and g_currentMission.hud.addMapHotspot ~= nil then
g_currentMission.hud:addMapHotspot(hotspot)
IAprintDebug("iaAddMapHotspotToMission()", string.format(
"[HOTSPOT] ADD ok via g_currentMission.hud:addMapHotspot name=%s",
label
), nil, nil, nil)
return true
end
IAprintDebug("iaAddMapHotspotToMission()", string.format(
"[HOTSPOT] ADD FAILED no addMapHotspot on mission/hud name=%s", label
), nil, nil, nil)
return false
end
function iaRemoveMapHotspotFromMission(hotspot)
if g_currentMission == nil or hotspot == nil then
IAprintDebug("iaRemoveMapHotspotFromMission()", string.format(
"[HOTSPOT] REMOVE skipped (g_currentMission=%s hotspot=%s)",
tostring(g_currentMission ~= nil), tostring(hotspot ~= nil)
), nil, nil, nil)
return
end
local label = tostring(hotspot.name ~= nil and hotspot:getName() or hotspot)
if g_currentMission.removeMapHotspot ~= nil then
g_currentMission:removeMapHotspot(hotspot)
IAprintDebug("iaRemoveMapHotspotFromMission()", string.format(
"[HOTSPOT] REMOVE ok via g_currentMission:removeMapHotspot name=%s yardPlaceKey=%s",
label, tostring(hotspot.iaFosBorrowYardPlaceKey)
), nil, nil, nil)
elseif g_currentMission.hud ~= nil and g_currentMission.hud.removeMapHotspot ~= nil then
g_currentMission.hud:removeMapHotspot(hotspot)
IAprintDebug("iaRemoveMapHotspotFromMission()", string.format(
"[HOTSPOT] REMOVE ok via g_currentMission.hud:removeMapHotspot name=%s",
label
), nil, nil, nil)
else
IAprintDebug("iaRemoveMapHotspotFromMission()", string.format(
"[HOTSPOT] REMOVE FAILED no removeMapHotspot on mission/hud name=%s", label
), nil, nil, nil)
end
end
--- Recursively set visibility on an i3d node and all descendants (skips nil / 0).
function iaSetNodeSubtreeVisible(nodeId, visible)
local vis = visible ~= false
if nodeId == nil or nodeId == 0 then
return
end
setVisibility(nodeId, vis)
for i = 0, getNumOfChildren(nodeId) - 1 do
iaSetNodeSubtreeVisible(getChildAt(nodeId, i), vis)
end
end
-- Debug print helper: method name + optional neighbour (id, name), vehicle (id, name), situation (id, intent).
-- Only prints when IANeighbours.debug is true.
-- @param string methodName - e.g. "IANeighbourVehicle:initialize()"
-- @param string message - Optional message to append after context
-- @param table neighbour - Optional IANeighbour (uses .id, .name)
-- @param table vehicle - Optional IANeighbourVehicle (uses .uniqueId, .vehicle:getFullName()) or vehicle object
-- @param table situation - Optional IASituation (uses .id, .config.intent)
function IAprintDebug(methodName, message, neighbour, vehicle, situation)
if IANeighbours == nil or not IANeighbours.debug then
return
end
local parts = { "--- ", tostring(methodName or "?") }
if neighbour and type(neighbour) == "table" then
local nid = neighbour.id ~= nil and tostring(neighbour.id) or "?"
local nname = neighbour.name ~= nil and tostring(neighbour.name) or "?"
parts[#parts + 1] = " | neighbour: " .. nid .. " " .. nname
end
if vehicle and type(vehicle) == "table" then
local vid, vname = "?", "?"
if vehicle.uniqueId ~= nil then
vid = tostring(vehicle.uniqueId)
end
if vehicle.vehicle and type(vehicle.vehicle.getFullName) == "function" then
vname = tostring(vehicle.vehicle:getFullName())
elseif type(vehicle.getFullName) == "function" then
vid = vid == "?" and "?" or vid
vname = tostring(vehicle:getFullName())
end
parts[#parts + 1] = " | vehicle: " .. vid .. " " .. vname
end
if situation and type(situation) == "table" then
local sid = situation.id ~= nil and tostring(situation.id) or "?"
local intent = "?"
if situation.config and situation.config.intent ~= nil then
intent = tostring(situation.config.intent)
elseif situation.intent ~= nil then
intent = tostring(situation.intent)
end
parts[#parts + 1] = " | situation: " .. sid .. " " .. intent
end
if message ~= nil and tostring(message) ~= "" then
parts[#parts + 1] = " - " .. tostring(message)
end
print(table.concat(parts))
-- [FOS_TEST] bridge: feed into structured test log when a test is running
if IATestRunner ~= nil and type(IATestRunner.emitDebug) == "function" then
IATestRunner.emitDebug(methodName, message, neighbour, vehicle, situation)
end
end
--- Run fn in pcall; on Lua error print when debug is enabled (IANeighbours.debug by default).
-- @param string label Full message prefix after "--- " (e.g. "IABorrowAccess.removeVehicleMapHotspot()")
-- @param function fn Zero-argument function
-- @param boolean|nil debugOverride If not nil, controls printing; if nil uses IANeighbours.debug when available
-- @return boolean ok True if pcall succeeded
function IAsafePcall(label, fn, debugOverride)
if type(fn) ~= "function" then
return false
end
local ok, err = pcall(fn)
local doPrint = false
if debugOverride ~= nil then
doPrint = debugOverride == true
else
doPrint = IANeighbours ~= nil and IANeighbours.debug == true
end
if not ok and doPrint then
print("--- " .. tostring(label) .. ": " .. tostring(err))
end
if ok then
IAprintDebug(label, "success", nil, nil, nil)
end
return ok
end
--- Trim leading/trailing whitespace; nil-safe. Used by conversation XML parsing and voice catalog keys.
function IAtrim(s)
if s == nil then
return ""
end
return tostring(s):match("^%s*(.-)%s*$") or ""
end
--- Display language "de" or "en" for UI-facing strings (voice pack overrides game language when loaded).
--- For audio paths and any UI showing voice-pack-dependent content. Uses `getGameUiLanguageCode` when no voice pack is loaded
--- so the same source of truth as `g_i18n:getText()` is used.
--- @return string "de" or "en"
function getDisplayLanguageCode()
--if IANeighbours ~= nil and IANeighbours.voicePackLoaded == true and IANeighbours.voicePackLanguage ~= nil and IANeighbours.voicePackLanguage ~= "" then
-- return IANeighbours.voicePackLanguage
--end
if g_i18n ~= nil and g_i18n:getText("gui_language") ~= nil then
return tostring(g_i18n:getText("gui_language"))
end
return "en"
end
function identifyAttachmentJoint(attachmentBack, vehicle)
local attachmentJoint = nil
local attachmentAttachIndex = nil
local attachmentNode = nil
local vehicleAttacherNode = nil
if attachmentBack == nil or type(attachmentBack) ~= "table" or attachmentBack.spec_attachable == nil or attachmentBack.spec_attachable.inputAttacherJoints == nil then
return nil, nil, nil, nil
end
if vehicle == nil or type(vehicle) ~= "table" or vehicle.spec_attacherJoints == nil or vehicle.spec_attacherJoints.attacherJoints == nil then
return nil, nil, nil, nil
end
for i,v in pairs(attachmentBack.spec_attachable.inputAttacherJoints) do
--print("--- IANeighbourVehicle:loadAttachmentBackById() - AttachmentBack attacher joint: "..tostring(i))
--printObj(v, 3, "attachmentBack-inputAttacherJoints-"..tostring(i))
local jointtype = v.jointType
for a,x in pairs(vehicle.spec_attacherJoints.attacherJoints) do
if x.jointType == jointtype and x.attacherJointDirection == -1 then -- -1 = rear, 1 = front
--printObj(x, 3, "attachmentBack-Vehicle-"..tostring(a))
--print("--- IANeighbourVehicle:loadAttachmentBackById() - Found matching joint: "..tostring(i))
--print("--- IANeighbourVehicle:loadAttachmentBackById() - Attaching attachment joint: "..tostring(i).." with tractor attachindex: "..tostring(a))
attachmentJoint = i
attachmentNode = v.node
vehicleAttachIndex = a
vehicleAttacherNode = x.jointTransform
break
end
end
break
end
if attachmentJoint == nil or vehicleAttachIndex == nil then
return nil, nil, nil, nil
end
return attachmentJoint, vehicleAttachIndex, attachmentNode, vehicleAttacherNode
end
-- Find a matching front attacher joint on the vehicle for the attachment (e.g. Header / Cutter).
-- @param table attachmentBack - The attachment vehicle (has spec_attachable.inputAttacherJoints)
-- @param table vehicle - The main vehicle (has spec_attacherJoints.attacherJoints)
-- @return number|nil attachmentJoint, number|nil vehicleAttachIndex, entityId|nil attachmentNode, entityId|nil vehicleAttacherNode
function identifyAttachmentJointFront(attachmentBack, vehicle)
local attachmentJoint = nil
local attachmentAttachIndex = nil
local attachmentNode = nil
local vehicleAttacherNode = nil
if attachmentBack == nil or type(attachmentBack) ~= "table" or attachmentBack.spec_attachable == nil or attachmentBack.spec_attachable.inputAttacherJoints == nil then
return nil, nil, nil, nil
end
if vehicle == nil or type(vehicle) ~= "table" or vehicle.spec_attacherJoints == nil or vehicle.spec_attacherJoints.attacherJoints == nil then
return nil, nil, nil, nil
end
for i,v in pairs(attachmentBack.spec_attachable.inputAttacherJoints) do
local jointtype = v.jointType
for a,x in pairs(vehicle.spec_attacherJoints.attacherJoints) do
if x.jointType == jointtype and x.attacherJointDirection == 1 then -- 1 = front
attachmentJoint = i
attachmentNode = v.node
vehicleAttachIndex = a
vehicleAttacherNode = x.jointTransform
break
end
end
break
end
if attachmentJoint == nil or vehicleAttachIndex == nil then
return nil, nil, nil, nil
end
return attachmentJoint, vehicleAttachIndex, attachmentNode, vehicleAttacherNode
end
-- True if the vehicle defines at least one front attacher joint (same convention as identifyAttachmentJointFront: attacherJointDirection == 1).
function vehicleHasFrontAttacherJoint(vehicle)
if vehicle == nil or type(vehicle) ~= "table" or vehicle.spec_attacherJoints == nil or vehicle.spec_attacherJoints.attacherJoints == nil then
return false
end
for _, x in pairs(vehicle.spec_attacherJoints.attacherJoints) do
if x ~= nil and x.attacherJointDirection == 1 then
return true
end
end
return false
end
-- Calculate the target world position for an attachment root node
-- so that the attachment's hook aligns with the vehicle's attacher
-- @param entityId vehicleRootNode - Root node of the vehicle
-- @param entityId attachmentRootNode - Root node of the attachment
-- @param entityId vehicleAttacherNode - Attacher (hook) node of the vehicle
-- @param entityId attachmentHookNode - Hook node of the attachment
-- @return number targetX, number targetY, number targetZ - World coordinates for attachment root node
function calculateAttachmentRootPosition(vehicleRootNode, attachmentRootNode, vehicleAttacherNode, attachmentHookNode)
-- Step 1: Get world coordinates of vehicle's attacher (where attachment hook should be)
local vehicleAttacherX, vehicleAttacherY, vehicleAttacherZ = getWorldTranslation(vehicleAttacherNode)
if IANeighbours.debug then
print("--- IAHelper:calculateAttachmentRootPosition() - Vehicle Attacher Position: "..tostring(vehicleAttacherX)..", "..tostring(vehicleAttacherY)..", "..tostring(vehicleAttacherZ))
end
-- Step 2: Calculate the offset from attachment hook to attachment root node
-- Get the hook's position in the root's local coordinate system
-- The hook's position in its own local space is (0, 0, 0), transform it to root's local space
local offsetX, offsetY, offsetZ = localToLocal(attachmentHookNode, attachmentRootNode, 0, 0, 0)
if IANeighbours.debug then
print("--- IAHelper:calculateAttachmentRootPosition() - Offset (root local space): "..tostring(offsetX)..", "..tostring(offsetY)..", "..tostring(offsetZ))
end
-- Convert the local offset to world space direction
local offsetWorldX, offsetWorldY, offsetWorldZ = localDirectionToWorld(vehicleAttacherNode, offsetX, offsetY, offsetZ)
if IANeighbours.debug then
print("--- IAHelper:calculateAttachmentRootPosition() - Offset (world space): "..tostring(offsetWorldX)..", "..tostring(offsetWorldY)..", "..tostring(offsetWorldZ))
end
--IANeighbours:addDebugPoint(offsetWorldX, offsetWorldY, offsetWorldZ,100,100,100,100)
-- Step 3: Calculate target world coordinates for attachment root node
-- Target root position = vehicle attacher position - offset from root to hook
local targetX = vehicleAttacherX - offsetWorldX
local targetY = vehicleAttacherY - offsetWorldY
local targetZ = vehicleAttacherZ - offsetWorldZ
--IANeighbours:addDebugPoint(targetX, targetY, targetZ,150,150,150,100)
local AttachmentHookX, AttachmentHookY, AttachmentHookZ = getWorldTranslation(attachmentHookNode)
--IANeighbours:addDebugPoint(vehicleAttacherNode)
--IANeighbours:addDebugPoint(attachmentRootNode)
--IANeighbours:addDebugPoint(attachmentHookNode)
return targetX, targetY, targetZ
end
function getFruitTypeGrowthStateName(fruitTypeIndex, growthState)
local fruitTypes = g_fruitTypeManager:getFruitTypes()
for _, fruitType in ipairs(fruitTypes) do
if fruitTypeIndex == fruitType.index then
for i, name in ipairs(fruitType.growthStateToName) do
--print("--- IAXMLHelper:saveFarmlands() - fruitType: "..tostring(fruitType.name).." - growthState: "..tostring(name).." - "..tostring(i).." - "..tostring(farmland.field.fieldState.growthState))
if i == growthState then
return name
end
end
end
end
end
function arrayToString(arr)
if arr == nil or type(arr) ~= "table" then
return tostring(arr)
end
local parts = {}
for _, v in ipairs(arr) do
parts[#parts + 1] = tostring(v)
end
return "{" .. table.concat(parts, ", ") .. "}"
end
-- Calculate the target world position for an attachment root node
-- so that the attachment's hook aligns with the vehicle's attacher
-- @param entityId vehicleRootNode - Root node of the vehicle
-- @param entityId attachmentRootNode - Root node of the attachment
-- @param entityId vehicleAttacherNode - Attacher (hook) node of the vehicle
-- @param entityId attachmentHookNode - Hook node of the attachment
-- @return number targetX, number targetY, number targetZ - World coordinates for attachment root node
function calculateAttachmentRootPosition2(vehicleRootNode, attachmentRootNode, vehicleAttacherNode, attachmentHookNode)
-- step 0: get offset of vehicle attacher
local vehicleAttacherOffsetX, vehicleAttacherOffsetY, vehicleAttacherOffsetZ = localToLocal(vehicleAttacherNode, vehicleRootNode, 0, 0, 0)
if IANeighbours.debug then
print("--- IAHelper:calculateAttachmentRootPosition() - Vehicle Attacher Offset (root local space): "..tostring(vehicleAttacherOffsetX)..", "..tostring(vehicleAttacherOffsetY)..", "..tostring(vehicleAttacherOffsetZ))
end
-- Step 1: Get vehicle's attacher world position
local vehicleX, vehicleY, vehicleZ = getWorldTranslation(vehicleRootNode)
-- Step 2: Get forward direction in world space (local 0,0,1 = forward)
local forwardX, forwardY, forwardZ = localDirectionToWorld(vehicleRootNode, 0, 0, 1)
-- Step 3: Calculate right direction using cross product (up × forward = right)
local rightX, rightY, rightZ = MathUtil.crossProduct(0, 1, 0, forwardX, forwardY, forwardZ)
-- Step 4: Get up direction in world space (local 0,1,0 = up)
local upX, upY, upZ = localDirectionToWorld(vehicleRootNode, 0, 1, 0)
-- Step 5: Calculate the offset from attachment hook to attachment root node
-- Get the hook's position in the root's local coordinate system
-- The hook's position in its own local space is (0, 0, 0), transform it to root's local space
local AttachmentHookOffsetX, AttachmentHookOffsetY, AttachmentHookOffsetZ = localToLocal(attachmentHookNode, attachmentRootNode, 0, 0, 0)
if IANeighbours.debug then
print("--- IAHelper:calculateAttachmentRootPosition() - Offset (root local space): "..tostring(AttachmentHookOffsetX)..", "..tostring(AttachmentHookOffsetY)..", "..tostring(AttachmentHookOffsetZ))
end
offsetX = 0--vehicleAttacherOffsetX + offsetX
offsetY = 0--vehicleAttacherOffsetY + offsetY
offsetZ = vehicleAttacherOffsetZ + (AttachmentHookOffsetZ*-1)
if IANeighbours.debug then
print("--- IAHelper:calculateAttachmentRootPosition() - Offset Z VehicleAttacherOffsetZ: "..tostring(vehicleAttacherOffsetZ)..", AttachmentHookOffsetZ: "..tostring(AttachmentHookOffsetZ)..", OffsetZ: "..tostring(offsetZ))
end
--local targetX = vehicleX + forwardX * offsetZ + rightX * offsetX + upX * offsetY
--local targetY = vehicleY + forwardY * offsetZ + rightY * offsetX + upY * offsetY
--local targetZ = vehicleZ + forwardZ * offsetZ + rightZ * offsetX + upZ * offsetY
local targetX, targetY, targetZ = getWorldPositionFromNodeLocalOffset(vehicleRootNode, offsetX, offsetY, offsetZ)
if targetX == nil then
return vehicleX, vehicleY, vehicleZ
end
--IANeighbours:addDebugPoint(vehicleAttacherNode)
--IANeighbours:addDebugPoint(attachmentRootNode)
--IANeighbours:addDebugPoint(attachmentHookNode)
--IANeighbours:addDebugPoint(vehicleRootNode)
return targetX, targetY, targetZ
end
--- World position = node world translation + localDirectionToWorld(node, localX, localY, localZ). Central resolver for placeable/map-node local offsets (IAMapPlace, etc.).
-- @param entityId node
-- @return number|nil worldX, number|nil worldY, number|nil worldZ
function getWorldPositionFromNodeLocalOffset(node, localX, localY, localZ)
if node == nil or not entityExists(node) or localDirectionToWorld == nil or getWorldTranslation == nil then
return nil, nil, nil
end
local nx, ny, nz = getWorldTranslation(node)
if nx == nil or nz == nil then
return nil, nil, nil
end
ny = ny or 0
local lx, ly, lz = localX or 0, localY or 0, localZ or 0
local dx, dy, dz = localDirectionToWorld(node, lx, ly, lz)
return nx + (dx or 0), ny + (dy or 0), nz + (dz or 0)
end
local iaHelperYawProbeTransform = nil
local function yawOnlyWorldXZAnalytic(centerX, centerZ, rotationY, localX, localZ)
local ry = rotationY or 0
local cosRy, sinRy = math.cos(ry), math.sin(ry)
local lx, lz = localX or 0, localZ or 0
return centerX + (lx * cosRy - lz * sinRy), centerZ + (lx * sinRy + lz * cosRy)
end
--- World position of (localX, localY, localZ) in a parent frame at world (worldX, worldY, worldZ) with Giants yaw only setRotation(0, rotationY, 0) — same as map-init corner debug parents. Uses localDirectionToWorld on a reused probe transform; analytic fallback if mission/API missing.
-- @param number rotationY - Yaw radians
function getWorldPositionFromYawLocalOffset(worldX, worldY, worldZ, rotationY, localX, localY, localZ)
if worldX == nil or worldZ == nil then
return nil, nil, nil
end
worldY = worldY or 0
local lx, ly, lz = localX or 0, localY or 0, localZ or 0
if g_currentMission == nil or g_currentMission.terrainRootNode == nil
or localDirectionToWorld == nil or setTranslation == nil or setRotation == nil or createTransformGroup == nil or link == nil then
local wx, wz = yawOnlyWorldXZAnalytic(worldX, worldZ, rotationY, lx, lz)
return wx, worldY + ly, wz
end
if iaHelperYawProbeTransform == nil or not entityExists(iaHelperYawProbeTransform) then
local pn = createTransformGroup("IAHelperYawProbe")
if pn ~= nil and pn ~= 0 then
link(g_currentMission.terrainRootNode, pn)
iaHelperYawProbeTransform = pn
end
end
local pn = iaHelperYawProbeTransform
if pn == nil or pn == 0 or not entityExists(pn) then
local wx, wz = yawOnlyWorldXZAnalytic(worldX, worldZ, rotationY, lx, lz)
return wx, worldY + ly, wz
end
setTranslation(pn, worldX, worldY, worldZ)
setRotation(pn, 0, rotationY or 0, 0)
local wdx, wdy, wdz = localDirectionToWorld(pn, lx, ly, lz)
return worldX + (wdx or 0), worldY + (wdy or 0), worldZ + (wdz or 0)
end
--- World position of a point at (localX, localY, localZ) in node's local space. Delegates to getWorldPositionFromNodeLocalOffset (localDirectionToWorld).
-- @param entityId node - Transform node (e.g. vehicle root or debug point node)
-- @param number localX - Offset in node's local X
-- @param number localY - Offset in node's local Y
-- @param number localZ - Offset in node's local Z
-- @return number|nil worldX, number|nil worldY, number|nil worldZ - World coordinates, or nil if node invalid
function getWorldPositionFromLocalOffset(node, localX, localY, localZ)
return getWorldPositionFromNodeLocalOffset(node, localX, localY, localZ)
end
--- Recursively find first child node with user attribute key equal to value (e.g. onCreate == "TrafficSystem.onCreate").
-- @param number node - Parent node
-- @param string key - User attribute name
-- @param string value - Expected value
-- @return number|nil - Child node id or nil
function findNodeByUserAttribute(node, key, value)
if node == nil or not entityExists(node) or key == nil or value == nil then
return nil
end
local n = getNumOfChildren(node)
for i = 0, n - 1 do
local child = getChildAt(node, i)
if child ~= nil and entityExists(child) then
local attr = getUserAttribute(child, key)
if attr == value then
return child
end
local found = findNodeByUserAttribute(child, key, value)
if found ~= nil then
return found
end
end
end
return nil
end
--- Max depth when walking traffic-root children for spline SHAPE nodes.
MAX_TRAFFIC_SPLINE_SEARCH_DEPTH = 24
-- getSplineLength must receive a SHAPE entity; pcall alone still triggers engine warnings on TRANSFORM nodes.
function safeGetSplineLength(nodeId)
if nodeId == nil or not entityExists(nodeId) or type(getSplineLength) ~= "function" then
return nil
end
if type(getHasClassId) == "function" and ClassIds ~= nil and ClassIds.SHAPE ~= nil then
if not getHasClassId(nodeId, ClassIds.SHAPE) then
return nil
end
end
local ok, len = pcall(getSplineLength, nodeId)
if not ok or len == nil or type(len) ~= "number" then
return nil
end
return len
end
function findSplineShapeInSubtree(nodeId, depthLeft)
if nodeId == nil or not entityExists(nodeId) then
return nil
end
local len = safeGetSplineLength(nodeId)
if len ~= nil and len >= 0.01 then
return nodeId
end
if depthLeft <= 0 then
return nil
end
local n = getNumOfChildren(nodeId)
for i = 0, n - 1 do
local child = getChildAt(nodeId, i)
if child ~= nil and entityExists(child) then
local found = findSplineShapeInSubtree(child, depthLeft - 1)
if found ~= nil then
return found
end
end
end
return nil
end
--- Unit direction (x,y,z) or nil if length near zero.
function normalizeVec3(x, y, z)
x, y, z = tonumber(x) or 0, tonumber(y) or 0, tonumber(z) or 0
local len = math.sqrt(x * x + y * y + z * z)
if len < 1e-6 then
return nil
end
return x / len, y / len, z / len
end
--- True if two place tables are the same logical slot (matching id or same position within tolerance).
function placesMatchForSituationBlocking(place1, place2)
if place1 == nil or place2 == nil then
return false
end
if place1.id ~= nil and place2.id ~= nil then
return place1.id == place2.id
end
local tolerance = 0.1
local xMatch = math.abs((place1.x or 0) - (place2.x or 0)) < tolerance
local yMatch = math.abs((place1.y or 0) - (place2.y or 0)) < tolerance
local zMatch = math.abs((place1.z or 0) - (place2.z or 0)) < tolerance
return xMatch and yMatch and zMatch
end
--- Low-level collision probe helper used by IANeighbours/IAMapPlace.
-- Runs `overlapSphere` at (x,y,z) and applies IANeighbours filtering:
-- terrain exclusion, collision filter group exclusion, node-name exclusion, and excludeNodeId subtree exclusion.
-- @param table neighbours - IANeighbours instance (used for constants/debug and overlap callback target)
-- @param table|nil extraExcludeNamePatterns optional array of lowercase substrings: node getName() matches if equal or contained (same rules as PLACE_BLOCKING_EXCLUDE_NODE_NAMES)
-- @return boolean blocked, table blockingInfos, table blockingNodeIds
function getPositionBlockedByCollision(neighbours, x, y, z, radiusM, excludeNodeId, extraExcludeNamePatterns)
if neighbours == nil or x == nil or z == nil or g_currentMission == nil or g_currentMission.terrainRootNode == nil then
return false, {}, {}
end
local function isNodeUnderTerrain(nodeId, terrainRootNode)
if nodeId == nil or terrainRootNode == nil or not entityExists(nodeId) then
return false
end
if nodeId == terrainRootNode then
return true
end
local n = nodeId
while n ~= nil and entityExists(n) do
local p = getParent(n)
if p == terrainRootNode then
return true
end
n = p
end
return false
end
local function isNodeDescendantOf(nodeId, ancestorId)
if nodeId == nil or ancestorId == nil or not entityExists(nodeId) or not entityExists(ancestorId) then
return false
end
if nodeId == ancestorId then
return true
end
local n = nodeId
while n ~= nil and entityExists(n) do
local p = getParent(n)
if p == ancestorId then
return true
end
n = p
end
return false
end
local function isNodeCollisionFilterGroupExcluded(nodeId, excludeGroups)
if nodeId == nil or excludeGroups == nil or type(excludeGroups) ~= "table" then
return false
end
local ok, group = pcall(function()
if getCollisionFilterGroup and type(getCollisionFilterGroup) == "function" then
return getCollisionFilterGroup(nodeId)
end
return nil
end)
if not ok or group == nil then
return false
end
local g = tonumber(group) or 0
for _, ex in ipairs(excludeGroups) do
if ex ~= nil and g == (tonumber(ex) or 0) then
return true
end
end
return false
end
--- Match local node name, full scene path, or any ancestor name (overlap often hits children under mapBoundaries, etc.).
local function lowerMatchesExcludePatterns(lowerStr)
if lowerStr == nil or lowerStr == "" then
return false
end
local list = neighbours.PLACE_BLOCKING_EXCLUDE_NODE_NAMES
if list ~= nil then
for _, pattern in ipairs(list) do
if pattern ~= nil then
local p = string.lower(tostring(pattern))
if p == lowerStr or (string.len(p) > 0 and string.find(lowerStr, p) ~= nil) then
return true
end
end
end
end
if extraExcludeNamePatterns ~= nil and type(extraExcludeNamePatterns) == "table" then
for _, pattern in ipairs(extraExcludeNamePatterns) do
if pattern ~= nil then
local p = string.lower(tostring(pattern))
if p == lowerStr or (string.len(p) > 0 and string.find(lowerStr, p) ~= nil) then
return true
end
end
end
end
-- Optional map-level whitelist from map config XML (fields_of_stories_<mapId>.xml <collisionWhitelist>)
local mapList = neighbours.mapCollisionExcludeNodeNames
if mapList ~= nil and type(mapList) == "table" then
for _, pattern in ipairs(mapList) do
if pattern ~= nil then
local p = string.lower(tostring(pattern))
if p == lowerStr or (string.len(p) > 0 and string.find(lowerStr, p) ~= nil) then
return true
end
end
end
end
return false
end
local function isNodeNameExcludedFromBlocking(nodeId)
if nodeId == nil then
return false
end
local ok, name = pcall(function()
if getName and type(getName) == "function" then
return getName(nodeId)
end
return nil
end)
if ok and name ~= nil and type(name) == "string" and lowerMatchesExcludePatterns(string.lower(name)) then
return true
end
local okF, fullPath = pcall(function()
if getNodeIdFullName and type(getNodeIdFullName) == "function" then
return getNodeIdFullName(nodeId)
end
return nil
end)
if okF and fullPath ~= nil and type(fullPath) == "string" and fullPath ~= "" and lowerMatchesExcludePatterns(string.lower(fullPath)) then
return true
end
local n, depth = nodeId, 0
while n ~= nil and depth < 64 do
local okP, parentId = pcall(function()
if getParent and type(getParent) == "function" then
return getParent(n)
end
return nil
end)
if not okP or parentId == nil or parentId == 0 then
break
end
local okAn, aname = pcall(function()
if getName and type(getName) == "function" then
return getName(parentId)
end
return nil
end)
if okAn and aname ~= nil and type(aname) == "string" and lowerMatchesExcludePatterns(string.lower(aname)) then
return true
end
n = parentId
depth = depth + 1
end
return false
end
local function getNodeDebugInfo(nodeId)
if nodeId == nil then
return "nil"
end
local ok, name = pcall(function()
if getName and type(getName) == "function" then
return getName(nodeId)
end
return nil
end)
if ok and name ~= nil and name ~= "" then
return tostring(name) .. " (id=" .. tostring(nodeId) .. ")"
end
local ok2, path = pcall(function()
if getNodeIdFullName and type(getNodeIdFullName) == "function" then
return getNodeIdFullName(nodeId)
end
return nil
end)
if ok2 and path ~= nil and path ~= "" then
return tostring(path) .. " (id=" .. tostring(nodeId) .. ")"
end
return "id=" .. tostring(nodeId)
end
local yVal = (y ~= nil) and y or 0
local radius = (radiusM ~= nil and radiusM > 0) and radiusM or neighbours.PLACE_COLLISION_CHECK_RADIUS
local collector = {}
neighbours._overlapCollectorIds = collector
local numShapes = 0
if overlapSphere then
local mask = neighbours.PLACE_OVERLAP_SPHERE_COLLISION_MASK
if mask ~= nil then
numShapes = overlapSphere(x, yVal, z, radius, "overlapCollectorCallback", neighbours, mask, true, true, true, false)
else
numShapes = overlapSphere(x, yVal, z, radius, "overlapCollectorCallback", neighbours)
end
end
neighbours._overlapCollectorIds = nil
if numShapes == 0 then
return false, {}, {}
end
local function isExcluded(nodeId, exclude)
if exclude == nil then return false end
if type(exclude) == "number" then
return isNodeDescendantOf(nodeId, exclude)
end
if type(exclude) ~= "table" then
return false
end
for _, exId in ipairs(exclude) do
if exId ~= nil and isNodeDescendantOf(nodeId, exId) then
return true
end
end
return false
end
local terrainRoot = g_currentMission.terrainRootNode
local blockingNodes = {}
local excludeFilterGroups = neighbours.PLACE_BLOCKING_EXCLUDE_COLLISION_FILTER_GROUPS
for _, nodeId in ipairs(collector) do
if nodeId ~= nil and not isNodeUnderTerrain(nodeId, terrainRoot) then
if excludeFilterGroups ~= nil and isNodeCollisionFilterGroupExcluded(nodeId, excludeFilterGroups) then
-- skip
elseif isNodeNameExcludedFromBlocking(nodeId) then
-- Exclude by name patterns (see PLACE_BLOCKING_EXCLUDE_NODE_NAMES)
elseif not isExcluded(nodeId, excludeNodeId) then
-- Exclude the main node and all nested children (e.g. place's own map node / building)
table.insert(blockingNodes, nodeId)
end
end
end
if #blockingNodes > 0 then
local blockingInfos = {}
for _, nid in ipairs(blockingNodes) do
table.insert(blockingInfos, getNodeDebugInfo(nid))
end
if neighbours.debug then
print(string.format("--- IANeighbours:isPositionBlockedByCollision() position=(%.2f, %.2f, %.2f) radius=%.2fm | %d overlap(s), %d non-terrain blocking | blocking: %s",
x, yVal, z, radius, #collector, #blockingNodes, table.concat(blockingInfos, " ; ")))
end
return true, blockingInfos, blockingNodes
end
return false, {}, {}
end
function distanceToPlayer(x,y,z)
if g_localPlayer ~= nil then
local playerX, playerY, playerZ = g_localPlayer:getPosition()
if x ~= nil and z ~= nil and playerX ~= nil and playerZ ~= nil then
--print("--- IANeighbour:update() - neighbourX: "..tostring(neighbourX)..", neighbourZ: "..tostring(neighbourZ)..", playerX: "..tostring(playerX)..", playerZ: "..tostring(playerZ))
-- Calculate 3D distance: sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)
local dx = playerX - x
local dy = (playerY or 0) - (y or 0)
local dz = playerZ - z
return math.sqrt(dx * dx + dy * dy + dz * dz)
end
end
return nil
end
--- Teleport the local player to world X/Z (dev/debug: iaForceFieldwork / iaForceSituation).
-- Uses Player:teleportTo when available; otherwise moves the current vehicle or the on-foot root node.
-- @param number|nil x
-- @param number|nil z
-- @return boolean true if a teleport was attempted
function IAHelper_teleportLocalPlayerToWorldXZ(x, z)
if g_localPlayer == nil or g_currentMission == nil then
return false
end
local tx = tonumber(x)
local tz = tonumber(z)
if tx == nil or tz == nil then
return false
end
if MathUtil ~= nil and type(MathUtil.round) == "function" then
tx = MathUtil.round(tx, 0)
tz = MathUtil.round(tz, 0)
end
local terrainNode = g_currentMission.terrainRootNode or g_terrainNode
local ty = 0
if terrainNode ~= nil and getTerrainHeightAtWorldPos ~= nil then
ty = getTerrainHeightAtWorldPos(terrainNode, tx, 0, tz) or 0
end
ty = ty + 0.2
local vehicle = g_localPlayer.getCurrentVehicle and g_localPlayer:getCurrentVehicle()
if vehicle ~= nil then
local rootVehicle = vehicle.rootVehicle or vehicle
if rootVehicle ~= nil and rootVehicle.rootNode ~= nil and entityExists(rootVehicle.rootNode) then
local wasInPhysics = rootVehicle.isAddedToPhysics == nil or rootVehicle:isAddedToPhysics()
if rootVehicle.removeFromPhysics ~= nil then
pcall(function() rootVehicle:removeFromPhysics() end)
end
if rootVehicle.setRelativePosition ~= nil then
pcall(function() rootVehicle:setRelativePosition(tx, 0.5, tz, 0, true) end)
else
pcall(function()
setTranslation(rootVehicle.rootNode, tx, ty, tz)
setRotation(rootVehicle.rootNode, 0, 0, 0)
end)
end
if wasInPhysics and rootVehicle.addToPhysics ~= nil then
pcall(function() rootVehicle:addToPhysics() end)
end
return true
end
end
if type(g_localPlayer.teleportTo) == "function" then
local ok = pcall(function() g_localPlayer:teleportTo(tx, ty, tz, true, true) end)
if ok then
return true
end
end
if g_localPlayer.rootNode ~= nil and entityExists(g_localPlayer.rootNode) then
setWorldTranslation(g_localPlayer.rootNode, tx, ty + 0.1, tz)
return true
end
return false
end
-- Terrain bounds helper (rectangle):
-- Uses mapWidth/mapHeight around terrain center (terrainRootNode world position, fallback 0,0).
-- @return table|nil bounds - { minX, maxX, minZ, maxZ } or nil if unavailable
function getTerrainBoundsRect()
if g_currentMission == nil then
return nil
end
local mapW = g_currentMission.mapWidth
local mapH = g_currentMission.mapHeight
if mapW == nil or mapH == nil or mapW <= 0 or mapH <= 0 then
return nil
end
local cx, _, cz = 0, 0, 0
if g_currentMission.terrainRootNode ~= nil and entityExists(g_currentMission.terrainRootNode) then
cx, _, cz = getWorldTranslation(g_currentMission.terrainRootNode)
end
local halfW = mapW * 0.5
local halfH = mapH * 0.5
return {
minX = cx - halfW,
maxX = cx + halfW,
minZ = cz - halfH,
maxZ = cz + halfH
}
end
-- Check if world position (x,z) is inside terrain bounds rectangle.
-- If bounds are unavailable, fail open (return true).
-- @param number x - world X
-- @param number z - world Z
-- @param table|nil bounds - Optional precomputed bounds from getTerrainBoundsRect()
-- @return boolean
function isWithinTerrainBoundsRect(x, z, bounds)
if x == nil or z == nil then
return false
end
local b = bounds or getTerrainBoundsRect()
if b == nil then
return true
end
return x >= b.minX and x <= b.maxX and z >= b.minZ and z <= b.maxZ
end
-- Normalize yaw to [-pi, pi].
-- @param number yaw
-- @return number
function normalizeYawPi(yaw)
local a = yaw or 0
while a > math.pi do
a = a - 2 * math.pi
end
while a < -math.pi do
a = a + 2 * math.pi
end
return a
end
-- Robust yaw extraction from node forward direction.
-- Uses localDirectionToWorld + MathUtil.getYRotationFromDirection to avoid Euler clamp artifacts.
-- @param entityId node
-- @param number fallbackYaw optional fallback when extraction fails
-- @return number yaw in radians
function getNodeYawFromForward(node, fallbackYaw)
if node == nil or not entityExists(node) then
return normalizeYawPi(fallbackYaw or 0)
end
local dirX, _, dirZ = localDirectionToWorld(node, 0, 0, 1)
if dirX == nil or dirZ == nil then
return normalizeYawPi(fallbackYaw or 0)
end
local yaw = (MathUtil and MathUtil.getYRotationFromDirection and MathUtil.getYRotationFromDirection(dirX, dirZ))
or math.atan2(dirX, dirZ)
return normalizeYawPi(yaw or fallbackYaw or 0)
end
--- In-game calendar month 1–12 from `environment.currentPeriod` (+2, with 13→1 / 14→2 wrap). Same rules as `getCurrentGameHours`.
--- @return number|nil
function getEnvironmentMonth1to12()
if g_currentMission == nil or g_currentMission.environment == nil then
return nil
end
local currentPeriod = g_currentMission.environment.currentPeriod or 0
local month = currentPeriod + 2
if month == 13 then
month = 1
elseif month == 14 then
month = 2
end
return month
end
--- Current savegame calendar parts for schedule invalidation (aligns with `getCurrentGameHours` month mapping).
--- @return number|nil year, number|nil month1to12, number|nil dayInPeriod
function getEnvironmentYearMonthDayInPeriod()
if g_currentMission == nil or g_currentMission.environment == nil then
return nil, nil, nil
end
local env = g_currentMission.environment
return env.currentYear, getEnvironmentMonth1to12(), env.currentDayInPeriod
end
--- In-game growth period index from `environment.currentPeriod` (same index used by fruit growth tables).
--- @return number|nil
function getEnvironmentCurrentPeriodOrNil()
if g_currentMission == nil or g_currentMission.environment == nil then