forked from Courseplay/courseplay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombineUnloadAIDriver.lua
1820 lines (1581 loc) · 74 KB
/
CombineUnloadAIDriver.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
This file is part of Courseplay (https://github.com/Courseplay/courseplay)
Copyright (C) 2020 Thomas Gärtner, Peter Vaiko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
How do we make sure the unloader does not collide with the combine?
1. ProximitySensor
The ProximitySensor is a generic AIDriver feature.
The combine has a proximity sensor on the back and will slow down and stop
if something is in range.
The unloader has a proximity sensor on the front to prevent running into the combine.
When unloading choppers, the tractor disables the generic speed control as it has to
drive very close to the chopper.
2. Turns
The combine stops when discharging during a turn, so at the end of a row or headland turn
it won't start the turn until it is empty.
3. Combine Ready For Unload
The unloader can also ask the combine if it is ready to unload (isReadyToUnload()), as we
expect the combine to know best when it is going to perform some maneuvers.
4. Cooperative Collision Avoidance Using the TrafficController
This is currently screwed up...
]]--
---@class CombineUnloadAIDriver : AIDriver
CombineUnloadAIDriver = CpObject(AIDriver)
CombineUnloadAIDriver.safetyDistanceFromChopper = 0.75
CombineUnloadAIDriver.targetDistanceBehindChopper = 1
CombineUnloadAIDriver.targetOffsetBehindChopper = 3 -- 3 m to the right
CombineUnloadAIDriver.targetDistanceBehindReversingChopper = 2
CombineUnloadAIDriver.minDistanceFromReversingChopper = 10
CombineUnloadAIDriver.minDistanceFromWideTurnChopper = 5
CombineUnloadAIDriver.safeManeuveringDistance = 30 -- distance to keep from a combine not ready to unload
CombineUnloadAIDriver.myStates = {
ON_FIELD = {},
ON_STREET = {},
WAITING_FOR_COMBINE_TO_CALL ={},
WAITING_FOR_PATHFINDER={},
FINDPATH_TO_TRACTOR={},
DRIVE_TO_COMBINE = {},
DRIVE_TO_TRACTOR={},
DRIVE_TO_UNLOAD_COURSE ={},
DRIVE_BESIDE_TRACTOR ={},
ALIGN_TO_TRACTOR = {},
GET_ALIGNCOURSE_TO_TRACTOR ={},
UNLOADING_MOVING_COMBINE ={},
UNLOADING_STOPPED_COMBINE = {},
FOLLOW_CHOPPER ={},
FOLLOW_TRACTOR = {},
DRIVE_BACK_FROM_REVERSING_COMBINE = {},
DRIVE_BACK_FROM_REVERSING_CHOPPER ={},
DRIVE_BACK_FROM_REVERSING_COMBINE_NOTURN = {},
DRIVE_BACK_FROM_EMPTY_COMBINE = {},
DRIVE_BACK_FROM_REVERSING_TRACTOR = {},
DRIVE_BACK_FROM_TURNINGCOMBINE = {},
DRIVE_BACK_FROM_TURNINGCHOPPER = {},
DRIVE_BACK_FULL ={},
HANDLE_COMBINE_TURN ={},
HANDLE_CHOPPER_HEADLAND_TURN = {},
HANDLE_CHOPPER_180_TURN = {},
FOLLOW_CHOPPER_THROUGH_TURN = {},
ALIGN_TO_CHOPPER_AFTER_TURN = {},
WAIT_FOR_CHOPPER_TURNED = {}
}
--- Constructor
function CombineUnloadAIDriver:init(vehicle)
courseplay.debugVehicle(11,vehicle,'CombineUnloadAIDriver:init()')
AIDriver.init(self, vehicle)
self.debugChannel = 4
self.mode = courseplay.MODE_COMBI
self:initStates(CombineUnloadAIDriver.myStates)
self.combineOffset = 0
self.distanceToCombine = math.huge
self.distanceToFront = 0
self.vehicle.cp.possibleCombines ={}
self.vehicle.cp.assignedCombines ={}
self.vehicle.cp.combinesListHUDOffset = 0
self.combineToUnloadReversing = 0
end
function CombineUnloadAIDriver:setHudContent()
courseplay.hud:setCombineUnloadAIDriverContent(self.vehicle)
end
function CombineUnloadAIDriver:debug(...)
local combineName = self.combineToUnload and nameNum(self.combineToUnload) or 'N/A'
courseplay.debugVehicle(self.debugChannel, self.vehicle, ' -> ' .. combineName .. ': ' .. string.format( ... ))
end
function CombineUnloadAIDriver:start(startingPoint)
self.myVehicleData = PathfinderUtil.VehicleData(self.vehicle)
self:beforeStart()
self:addForwardProximitySensor()
self.state = self.states.RUNNING
self.unloadCourse = Course(self.vehicle, self.vehicle.Waypoints)
-- just to have a course set up in any case for PPC to work with until we find a combine/path
self:startCourse(self.unloadCourse, 1)
if startingPoint:is(StartingPointSetting.START_WITH_UNLOAD) then
self:debug('Start unloading, waiting for a combine to call')
self:setNewState(self.states.ON_FIELD)
self:setNewOnFieldState(self.states.WAITING_FOR_COMBINE_TO_CALL)
self:disableCollisionDetection()
self:setDriveUnloadNow(false)
else
self:debug('Start on unload course')
local ix = self.unloadCourse:getStartingWaypointIx(AIDriverUtil.getDirectionNode(self.vehicle), startingPoint)
self:startCourseWithPathfinding(self.unloadCourse, ix, 0, 0)
self:setNewState(self.states.ON_STREET)
end
self.distanceToFront = 0
end
function CombineUnloadAIDriver:dismiss()
local x,_,z = getWorldTranslation(self:getDirectionNode())
if self.combineToUnload then
self.combineToUnload.cp.driver:deregisterUnloader(self)
end
self:releaseUnloader()
if courseplay:isField(x, z) then
self:setNewState(self.states.ON_FIELD)
self:setNewOnFieldState(self.states.WAITING_FOR_COMBINE_TO_CALL)
end
AIDriver.dismiss(self)
end
function CombineUnloadAIDriver:drive(dt)
courseplay:updateFillLevelsAndCapacities(self.vehicle)
self:updateCombineStatus()
if self.state == self.states.ON_STREET then
if not self:onUnLoadCourse(true, dt) then
self:hold()
end
-- disable speed control as it messes up the speed control during unload
-- TODO: refactor that whole unload process, it was just copied from the legacy CP code
self.forwardLookingProximitySensorPack:disableSpeedControl()
self:searchForTipTriggers()
AIDriver.drive(self, dt)
elseif self.state == self.states.ON_FIELD then
local renderOffset = self.vehicle.cp.coursePlayerNum * 0.03
self:renderText(0, 0.1 + renderOffset, "%s: self.onFieldState :%s", nameNum(self.vehicle), self.onFieldState.name)
self:driveOnField(dt)
end
end
function CombineUnloadAIDriver:stopAndWait(dt)
self:driveInDirection(dt,0,1,true,0,false)
end
function CombineUnloadAIDriver:driveInDirection(dt,lx,lz,fwd,speed,allowedToDrive)
--AIVehicleUtil.driveInDirection(self.vehicle, dt, self.vehicle.cp.steeringAngle, 1, 0.5, 10, allowedToDrive, fwd, lx, lz, speed, 1)
-- TODO: use this directly everywhere, seems to work better than the vanilla AIVehicleUtil version
self:driveVehicleInDirection(dt, allowedToDrive, fwd, lx, lz, speed)
end
function CombineUnloadAIDriver:driveOnField(dt)
self:drawDebugInfo()
-- make sure if we have a combine we stay registered
if self.combineToUnload then
self.combineToUnload.cp.driver:registerUnloader(self)
end
-- safety check: combine has active AI driver
if self.combineToUnload and not self.combineToUnload.cp.driver:isActive() then
self:setSpeed(0)
end
if self.vehicle.cp.forcedToStop then
self:stopAndWait(dt)
return
end
if self.onFieldState == self.states.WAITING_FOR_COMBINE_TO_CALL then
local combineToWaitFor
if self:getDriveUnloadNow() or self:getAllTrailersFull() or self:shouldDriveOn() then
self:debug('Was waiting for a combine but drive now requested or trailer full')
self:startUnloadCourse()
return
end
-- check for an available combine but not in every loop, not needed
if g_updateLoopIndex % 100 == 0 then
self.combineToUnload, combineToWaitFor = g_combineUnloadManager:giveMeACombineToUnload(self.vehicle)
if self.combineToUnload ~= nil then
self:refreshHUD()
courseplay:openCloseCover(self.vehicle, courseplay.OPEN_COVERS)
-- TODO: for now, only unloading stopped combine
if self:isOkToStartUnloadingCombine() then
self:startUnloadingCombine()
elseif self:isOkToStartFollowingChopper() then
self:startFollowingChopper()
else
self:startPathfindingToCombine(self.onPathfindingDoneToCombine)
end
else
if combineToWaitFor then
courseplay:setInfoText(self.vehicle, string.format("COURSEPLAY_WAITING_FOR_FILL_LEVEL;%s", nameNum(combineToWaitFor)));
else
courseplay:setInfoText(self.vehicle, "COURSEPLAY_NO_COMBINE_IN_REACH");
end
end
end
self:hold()
elseif self.onFieldState == self.states.WAITING_FOR_PATHFINDER then
-- just wait for the pathfinder to finish
self:setSpeed(0)
elseif self.onFieldState == self.states.FINDPATH_TO_TRACTOR then
--get coords of the combine
local zOffset = -20
local cx,cy,cz = localToWorld(self.tractorToFollow.rootNode,0,0,zOffset)
if not courseplay:isField(cx,cz,0.1,0.1) then
zOffset = 0
end
if self:driveToNodeWithPathfinding(self.tractorToFollow.rootNode, 0, zOffset, 0, self.tractorToFollow) then
self:setNewOnFieldState(self.states.DRIVE_TO_TRACTOR)
self.lastTractorsCoords = { x=cx;
y=cy;
z=cz;
}
end
elseif self.onFieldState == self.states.DRIVE_TO_TRACTOR then
self.forwardLookingProximitySensorPack:enableSpeedControl()
--if I'm the first Unloader switch to follow chopper
if g_combineUnloadManager:getUnloadersNumber(self.vehicle, self.combineToUnload) == 1 then
self:setNewOnFieldState(self.states.WAITING_FOR_PATHFINDER)
end
--check whether the tractor moved meanwhile
if courseplay:distanceToPoint(self.tractorToFollow,self.lastTractorsCoords.x,self.lastTractorsCoords.y,self.lastTractorsCoords.z) > 50 then
self:setNewOnFieldState(self.states.FINDPATH_TO_TRACTOR)
end
--if we are in range , change to align mode
local cx,cy,cz = getWorldTranslation(self.combineToUnload.rootNode)
if courseplay:distanceToPoint(self.vehicle,cx,cy,cz) < 50 then
self:setNewOnFieldState(self.states.GET_ALIGNCOURSE_TO_TRACTOR)
end
--use trafficController
if not self:trafficControlOK() then
local blockingVehicle = g_currentMission.nodeToObject[g_trafficController:getBlockingVehicleId(self.vehicle.rootNode)]
if blockingVehicle and blockingVehicle ~= self.tractorToFollow then
g_trafficController:solve(self.vehicle.rootNode)
self:hold()
end
else
g_trafficController:resetSolver(self.vehicle.rootNode)
end
elseif self.onFieldState == self.states.DRIVE_TO_COMBINE then
self.forwardLookingProximitySensorPack:enableSpeedControl()
courseplay:setInfoText(self.vehicle, "COURSEPLAY_DRIVE_TO_COMBINE");
--check whether the combine moved meanwhile
--if courseplay:distanceToPoint(self.combineToUnload,self.lastCombinesCoords.x,self.lastCombinesCoords.y,self.lastCombinesCoords.z) > 50 then
-- self:setNewOnFieldState(self.states.WAITING_FOR_PATHFINDER)
--end
self:setFieldSpeed()
--use trafficController
if not self:trafficControlOK() then
self:debugSparse('Traffic conflict, stop.')
self:hold()
end
-- stop when too close to a combine not ready to unload (wait until it is done with turning for example)
if self:isWithinSafeManeuveringDistance() then
self:debugSparse('Too close to maneuvering combine, stop.')
-- self:hold()
else
self:setFieldSpeed()
end
if self:isOkToStartUnloadingCombine() then
self:startUnloadingCombine()
elseif self:isOkToStartFollowingChopper() then
self:startFollowingChopper()
end
elseif self.onFieldState == self.states.UNLOADING_STOPPED_COMBINE then
self:unloadStoppedCombine()
elseif self.onFieldState == self.states.GET_ALIGNCOURSE_TO_TRACTOR then
local tempCourseToAlign = self:getCourseToAlignTo(self.tractorToFollow,0)
if tempCourseToAlign ~= nil then
self:startCourseWithAlignment(tempCourseToAlign, 1)
self:setNewOnFieldState(self.states.ALIGN_TO_TRACTOR)
end
elseif self.onFieldState == self.states.ALIGN_TO_TRACTOR then
courseplay:setInfoText(self.vehicle, "COURSEPLAY_FOLLOWING_TRACTOR");
if self:tractorIsReversing() then
self:hold()
end
--if we are in range , change to follow mode
local sx,sy,sz = getWorldTranslation(self.vehicle.rootNode)
local dx,dy,dz = worldToLocal(self.tractorToFollow.rootNode,sx,sy,sz)
if math.abs(dx)< 2 and dz > -40 and dz < 0 then
self:setNewOnFieldState(self.states.FOLLOW_TRACTOR)
end
--use trafficController
if not self:trafficControlOK() then
local blockingVehicle = g_currentMission.nodeToObject[g_trafficController:getBlockingVehicleId(self.vehicle.rootNode)]
if blockingVehicle and blockingVehicle ~= self.tractorToFollow then
g_trafficController:solve(self.vehicle.rootNode)
self:hold()
end
else
g_trafficController:resetSolver(self.vehicle.rootNode)
end
elseif self.onFieldState == self.states.UNLOADING_MOVING_COMBINE then
self.forwardLookingProximitySensorPack:disableSpeedControl()
self:unloadMovingCombine(dt)
elseif self.onFieldState == self.states.FOLLOW_CHOPPER then
self:followChopper()
elseif self.onFieldState == self.states.FOLLOW_TRACTOR then
courseplay:setInfoText(self.vehicle, "COURSEPLAY_FOLLOWING_TRACTOR");
-- if the tractor is nearly full, pull over to take over the pipe
if self:getTractorsFillLevelPercent() > 90 and self:getChopperOffset(self.combineToUnload) ~= 0 then
self:setNewOnFieldState(self.states.DRIVE_BESIDE_TRACTOR)
end
--if I'm the first Unloader switch to follow chopper
if g_combineUnloadManager:getUnloadersNumber(self.vehicle, self.combineToUnload) == 1 then
self:setNewOnFieldState(self.states.FOLLOW_CHOPPER)
end
self:setSavedCombineOffset(self.tractorToFollow.cp.combineOffset)
--if chopper is turning , wait till turn is done
if self:getCombineIsTurning() then
self:hold()
elseif not self.allowedToDrive then
--reset because AIDriver:resetSpeed() is not called here
self:resetSpeed()
end
--if the tractor is reversing, drive backwards
if self:tractorIsReversing() then
local reverseCourse = self:getStraightReverseCourse()
AIDriver.startCourse(self,reverseCourse,1)
self:setNewOnFieldState(self.states.DRIVE_BACK_FROM_REVERSING_TRACTOR )
end
self:driveBehindTractor(dt)
return
elseif self.onFieldState == self.states.DRIVE_BESIDE_TRACTOR then
if g_combineUnloadManager:getUnloadersNumber(self.vehicle, self.combineToUnload) == 1 then
self:setNewOnFieldState(self.states.FOLLOW_CHOPPER)
end
if self:getCombineIsTurning() then
self:hold()
end
self:driveBesideTractor(dt)
return
elseif self.onFieldState == self.states.HANDLE_CHOPPER_HEADLAND_TURN then
self:handleChopperHeadlandTurn()
elseif self.onFieldState == self.states.HANDLE_CHOPPER_180_TURN then
self:handleChopper180Turn()
elseif self.onFieldState == self.states.ALIGN_TO_CHOPPER_AFTER_TURN then
self:alignToChopperAfterTurn()
elseif self.onFieldState == self.states.FOLLOW_CHOPPER_THROUGH_TURN then
self:followChopperThroughTurn()
elseif self.onFieldState == self.states.DRIVE_TO_UNLOAD_COURSE then
--use trafficController
if not self:trafficControlOK() then
-- TODO: don't solve anything for now, just wait
--g_trafficController:solve(self.vehicle.rootNode)
self:hold()
else
g_trafficController:resetSolver(self.vehicle.rootNode)
end
elseif self.onFieldState == self.states.WAIT_FOR_CHOPPER_TURNED then
--print("self.combineToUnload.cp.turnStage: "..tostring(self.combineToUnload.cp.turnStage))
self:hold()
if self.combineToUnload.cp.turnStage == 0 then
self:setNewOnFieldState(self.states.FOLLOW_CHOPPER)
end
elseif self.onFieldState == self.states.DRIVE_BACK_FULL then
local _, dx, dz = self:getDistanceFromCombine()
-- drive back way further if we are behind a chopper to have room
local dDriveBack = dx < 3 and 0.75 * self.vehicle.cp.turnDiameter or 0
if dz > dDriveBack then
self:releaseUnloader()
self:startUnloadCourse()
else
self:holdCombine()
end
if self:getImFirstOfTwoUnloaders() and self:getChopperOffset(self.combineToUnload) ~= 0 then
if not self:getCombineIsTurning() then
if not self.combineToUnload.cp.driver:isStopped() then
self:hold()
end
else
self:holdCombine()
end
end
elseif self.onFieldState == self.states.DRIVE_BACK_FROM_EMPTY_COMBINE then
-- drive back until the combine is in front of us
local _, _, dz = self:getDistanceFromCombine()
if dz > 0 then
self:releaseUnloader()
self:setNewOnFieldState(self.states.WAITING_FOR_COMBINE_TO_CALL)
else
self:holdCombine()
end
elseif self.onFieldState == self.states.DRIVE_BACK_FROM_TURNINGCHOPPER then
local z = self:getZOffsetToCoordsBehind()
if z > 5 then
self:setNewOnFieldState(self.states.HANDLE_CHOPPER_HEADLAND_TURN)
else
self:holdCombine()
end
elseif self.onFieldState == self.states.DRIVE_BACK_FROM_REVERSING_CHOPPER then
self:renderText(0, 0, "drive straight reverse :offset local :%s saved:%s", tostring(self.combineOffset), tostring(self.vehicle.cp.combineOffset))
local d = self:getDistanceFromCombine()
local combineSpeed = (self.combineToUnload.lastSpeedReal * 3600)
local speed = combineSpeed + MathUtil.clamp(self.minDistanceFromReversingChopper - d, -combineSpeed, self.vehicle.cp.speeds.reverse * 1.5)
self:renderText(0, 0.7, 'd = %.1f, distance diff = %.1f speed = %.1f', d, self.minDistanceFromReversingChopper - d, speed)
-- keep 15 m distance from chopper
self:setSpeed(speed)
if not self:isMyCombineReversing() then
-- resume forward course
self:startCourse(self.followCourse, self.followCourse:getCurrentWaypointIx())
self:setNewOnFieldState(self.states.HANDLE_CHOPPER_HEADLAND_TURN)
end
elseif self.onFieldState == self.states.DRIVE_BACK_FROM_REVERSING_COMBINE_NOTURN then
self:renderText(0, 0, "drive straight reverse :offset local :%s saved:%s", tostring(self.combineOffset), tostring(self.vehicle.cp.combineOffset))
--local dx,dy,dz = self.course:getWaypointLocalPosition(self:getDirectionNode(), 1)
local _, _, dz = localToLocal(AIDriverUtil.getDirectionNode(self.vehicle), AIDriverUtil.getDirectionNode(self.combineToUnload), 0, 0, 0)
if dz < -10 then
self:hold()
else
local z = self:getZOffsetToCoordsBehind()
if z < 5 then
self:holdCombine()
end
end
if not self.combineToUnload.cp.driver.ppc:isReversing() then
if self:combineIsMakingPocket() then
self:hold()
else
self:setNewOnFieldState(self.states.UNLOADING_MOVING_COMBINE)
end
end
elseif self.onFieldState == self.states.DRIVE_BACK_FROM_REVERSING_TRACTOR then
if not self:tractorIsReversing() then
self:setNewOnFieldState(self.states.FOLLOW_TRACTOR)
end
end
AIDriver.drive(self, dt)
end
function CombineUnloadAIDriver:getTractorsFillLevelPercent()
return self.tractorToFollow.cp.totalFillLevelPercent
end
function CombineUnloadAIDriver:getFillLevelPercent()
return self.vehicle.cp.totalFillLevelPercent
end
function CombineUnloadAIDriver:holdCombine()
self:debugSparse('Holding combine.')
self.combineToUnload.cp.driver:hold()
end
function CombineUnloadAIDriver:getRecordedSpeed()
-- default is the street speed (reduced in corners)
if self.state == self.states.ON_STREET then
local speed = self:getDefaultStreetSpeed(self.ppc:getCurrentWaypointIx()) or self.vehicle.cp.speeds.street
if self.vehicle.cp.speeds.useRecordingSpeed then
-- use default street speed if there's no recorded speed.
speed = math.min(self.course:getAverageSpeed(self.ppc:getCurrentWaypointIx(), 4) or speed, speed)
end
--course end
if self.ppc:getCurrentWaypointIx()+3 >= self.course:getNumberOfWaypoints() then
speed= self.vehicle.cp.speeds.approach
end
return speed
else
return self.vehicle.cp.speeds.field
end
end
function CombineUnloadAIDriver:driveBesideCombine(targetNode)
-- TODO: this + 2 is a workaround the fact that we use a simple P controller instead of a PI
local _, _, dz = localToLocal(targetNode, self.combineToUnload.rootNode, 0, 0, - self.combineToUnload.cp.driver.pipeOffsetZ - 2)
-- use a factor of two to make sure we reach the pipe fast
local speed = self.combineToUnload.lastSpeedReal * 3600 + MathUtil.clamp(-dz * 1.5, -10, 15)
self:renderText(0, 0.02, "%s: driveBesideCombine: dz = %.1f, speed = %.1f", nameNum(self.vehicle), dz, speed)
DebugUtil.drawDebugNode(targetNode, 'target')
self:setSpeed(math.max(0, speed))
end
function CombineUnloadAIDriver:driveBesideChopper(dt,targetNode)
self:renderText(0, 0.02,"%s: driveBesideCombine:offset local :%s saved:%s",nameNum(self.vehicle),tostring(self.combineOffset),tostring(self.vehicle.cp.combineOffset))
self:releaseAutoAimNode()
local _, _, dz = localToLocal(targetNode, self.combineToUnload.rootNode, 0, 0, 5)
renderText(0.2,0.325,0.02,string.format("dz: %.1f", dz))
self:setSpeed(math.max(0, (self.combineToUnload.lastSpeedReal * 3600) + (MathUtil.clamp(-dz, -10, 15))))
end
function CombineUnloadAIDriver:driveBehindChopper(dt)
self:renderText(0, 0.05, "%s: driveBehindChopper offset local :%s saved:%s",nameNum(self.vehicle),tostring(self.combineOffset),tostring(self.vehicle.cp.combineOffset))
self:fixAutoAimNode()
--get required Speed
self:setSpeed(self:getSpeedBehindChopper())
end
function CombineUnloadAIDriver:driveBehindCombine(dt)
self:renderText(0, 0.05, "%s: driveBehindCombine offset local :%s saved:%s",nameNum(self.vehicle),tostring(self.combineOffset),tostring(self.vehicle.cp.combineOffset))
local allowedToDrive = true
local fwd = true
--get direction to drive to
local gx,gy,gz = self:getDrivingCoordsBehind(self.combineToUnload)
local lx,lz = AIVehicleUtil.getDriveDirection(self.vehicle.cp.directionNode, gx,gy,gz);
--get required Speed
local speed = self:getSpeedBehindCombine()
--I'm not behind the combine and have to wait till i can get behind it
local z = self:getZOffsetToCoordsBehind()
if z < 0 then
--print("STOOOOOOP")
allowedToDrive = false
else
self:setSavedCombineOffset(self.combineOffset)
end
self:driveInDirection(dt,lx,lz,fwd,speed,allowedToDrive)
--AIVehicleUtil.driveInDirection(self.vehicle, dt, self.vehicle.cp.steeringAngle, 1, 0.5, 10, allowedToDrive, fwd, lx, lz, speed, 1)
end
function CombineUnloadAIDriver:driveBehindTractor(dt)
local allowedToDrive = true
local fwd = true
--get direction to drive to
local gx,gy,gz = self:getDrivingCoordsBehindTractor(self.tractorToFollow)
local lx,lz = AIVehicleUtil.getDriveDirection(self.vehicle.cp.directionNode, gx,gy,gz);
--get required Speed
local speed = self:getSpeedBehindTractor(self.tractorToFollow)
if not courseplay:isField(gx, gz) then
allowedToDrive = false
end
allowedToDrive = allowedToDrive and self.allowedToDrive
self:renderText(0, 0.05, "%s: driveBehindTractor distance: %.2f",nameNum(self.vehicle),courseplay:distanceToObject(self.vehicle, self.tractorToFollow))
self:driveInDirection(dt,lx,lz,fwd,speed,allowedToDrive)
--AIVehicleUtil.driveInDirection(self.vehicle, dt, self.vehicle.cp.steeringAngle, 1, 0.5, 10, allowedToDrive, fwd, lx, lz, speed, 1)
end
function CombineUnloadAIDriver:driveBesideTractor(dt)
local allowedToDrive = true
local speed = 0
local fwd = true
--get direction to drive to
local gx,gy,gz = self:getDrivingCoordsBesideTractor(self.tractorToFollow)
local lx,lz = AIVehicleUtil.getDriveDirection(self.vehicle.cp.directionNode, gx,gy,gz);
--get required Speed
local targetNode = self:getTrailersTargetNode()
speed, allowedToDrive = self:getSpeedBesideChopper(targetNode)
allowedToDrive = allowedToDrive and self.allowedToDrive
self:renderText(0, 0.05, "driveBesideTractor distance: %.2f",courseplay:distanceToObject(self.vehicle, self.tractorToFollow))
self:driveInDirection(dt,lx,lz,fwd,speed,allowedToDrive)
--AIVehicleUtil.driveInDirection(self.vehicle, dt, self.vehicle.cp.steeringAngle, 1, 0.5, 10, allowedToDrive, fwd, lx, lz, speed, 1)
end
function CombineUnloadAIDriver:onEndCourse()
if self.state == self.states.ON_STREET then
self:setNewState(self.states.ON_FIELD)
self:setNewOnFieldState(self.states.WAITING_FOR_COMBINE_TO_CALL)
self:setDriveUnloadNow(false)
courseplay:openCloseCover(self.vehicle, courseplay.OPEN_COVERS)
self:disableCollisionDetection()
end
end
function CombineUnloadAIDriver:onLastWaypoint()
if self.state == self.states.ON_FIELD then
if self.onFieldState == self.states.DRIVE_TO_UNLOAD_COURSE then
self:setNewState(self.states.ON_STREET)
self:setNewOnFieldState(self.states.WAITING_FOR_COMBINE_TO_CALL)
self:enableCollisionDetection()
courseplay:openCloseCover(self.vehicle, courseplay.CLOSE_COVERS)
AIDriver.onLastWaypoint(self)
g_trafficController:cancel(self.vehicle.rootNode)
return
elseif self.onFieldState == self.states.ALIGN_TO_TRACTOR then
self:setNewOnFieldState(self.states.FOLLOW_TRACTOR)
g_trafficController:cancel(self.vehicle.rootNode)
elseif self.onFieldState == self.states.DRIVE_TO_COMBINE then
g_trafficController:cancel(self.vehicle.rootNode)
if self:isOkToStartUnloadingCombine() then
self:startUnloadingCombine()
elseif self:isOkToStartFollowingChopper() then
self:startFollowingChopper()
else
self:debug('reached last waypoint, combine isn\'t here anymore, find path to it again')
self:startPathfindingToCombine(self.onPathfindingDoneToCombine, 0, -20)
end
end
end
AIDriver.onLastWaypoint(self)
end
function CombineUnloadAIDriver:setFieldSpeed()
if self.course then
-- slow down a bit towards the end of the course.
if self.course:getNumberOfWaypoints() - self.course:getCurrentWaypointIx() < 10 then
self:setSpeed(self.vehicle.cp.speeds.field / 2)
else
self:setSpeed(self.vehicle.cp.speeds.field)
end
end
end
function CombineUnloadAIDriver:setNewState(newState)
self.state = newState
self:debug('setNewState: %s', self.state.name)
end
function CombineUnloadAIDriver:setNewOnFieldState(newState)
self.onFieldState = newState
self:debug('setNewOnFieldState: %s', self.onFieldState.name)
end
function CombineUnloadAIDriver:getCourseToAlignTo(vehicle,offset)
local waypoints = {}
for i=-20,20,5 do
local x,y,z = localToWorld(vehicle.rootNode,offset,0,i)
local point = { cx = x;
cy = y;
cz = z;
}
table.insert(waypoints,point)
end
local tempCourse = Course(self.vehicle,waypoints)
return tempCourse
end
function CombineUnloadAIDriver:getStraightReverseCourse()
local waypoints = {}
for i=0, -100, -5 do
local x, y, z = localToWorld(self.trailerToFill.rootNode, 0, 0, i)
table.insert(waypoints, {x = x, y = y, z = z, rev = true})
end
return Course(self.vehicle, waypoints, true)
end
function CombineUnloadAIDriver:getTrailersTargetNode()
local allTrailersFull = true
for i=1,#self.vehicle.cp.workTools do
local tipper = self.vehicle.cp.workTools[i]
--tipper.spec_fillUnit.fillUnits[1].fillLevel =100
local fillUnits = tipper:getFillUnits()
for j=1,#fillUnits do
local tipperFillType = tipper:getFillUnitFillType(j)
local combineFillType = self.combineToUnload and self.combineToUnload:getFillUnitLastValidFillType(self.combineToUnload:getCurrentDischargeNode().fillUnitIndex) or FillType.UNKNOWN
if tipper:getFillUnitFreeCapacity(j) > 0 then
allTrailersFull = false
if tipperFillType == FillType.UNKNOWN or tipperFillType == combineFillType or combineFillType == FillType.UNKNOWN then
local targetNode = tipper:getFillUnitAutoAimTargetNode(1)
if targetNode ~= nil then
self.trailerToFill = tipper
return targetNode, allTrailersFull
end
end
end
end
end
return nil,allTrailersFull
end
function CombineUnloadAIDriver:getDrivingCoordsBeside()
-- TODO: use localToLocal
-- target position 5 m in front of the tractor
local tx, ty, tz = localToWorld(AIDriverUtil.getDirectionNode(self.vehicle), 0, 0, 5)
-- tractor's local position in the combine's coordinate system
local sideShift, _, backShift = worldToLocal(self.combineToUnload.cp.directionNode, tx, ty, tz)
local backDistance = self:getCombinesMeasuredBackDistance() + 3
-- unit vector from the combine to the target
local origLx, origLz = AIVehicleUtil.getDriveDirection(self.combineToUnload.cp.directionNode, tx, ty, tz)
local lx, lz = origLx, origLz
local isBeside = false
if self.combineOffset > 0 then
-- pipe on the right
lx = math.max(0.25, lx)
--if I'm on the wrong side, drive to combines back first
if backShift > 0 and sideShift < 0 then
-- front of the combine or on the left
lx = 0
lz= -1
end
else
lx = math.min(-0.25, lx)
--if I'm on the wrong side, drive to combines back first
if backShift > 0 and sideShift > 0 then
-- front of the combine or on the right
lx = 0
lz= -1
end
end
-- no idea how are we calculating this, especially the backDistance part does not seem to make sense with lx
local rayLength = (math.abs(self.combineOffset)*math.abs(lx)) + (backDistance - (backDistance * math.abs(lx)))
-- this is waaay too complicated, why not just use
local nx, _, nz = localDirectionToWorld(self.combineToUnload.cp.directionNode, lx, 0, lz)
local cx, cy, cz = getWorldTranslation(self.combineToUnload.cp.directionNode)
local x, y, z = cx + (nx * rayLength), cy, cz + (nz * rayLength)
local offsetDifference = self.combineOffset - sideShift
--self:debug('lz %.1f, lx %.1f, raylength %.1f, backdistance %.1f, sideshift %.1f, backsift %.1f', lz, lx, rayLength, backDistance, sideShift , backShift)
local distanceToTarget = courseplay:distance(tx, tz, x, z)
--we are on the correct side but not close to the target point, so got directly to the offsetTarget
if self.combineOffset > 0 then
if origLx > 0 then
--print("distanceToTarget: "..tostring(distanceToTarget))
isBeside = distanceToTarget > 4
end
else
if origLx < 0 then
--print("distanceToTarget: "..tostring(distanceToTarget))
isBeside = distanceToTarget > 4
end
end
isBeside = isBeside or math.abs(offsetDifference) < 0.5
if lz > 0 or isBeside then
x, y, z = localToWorld(self.combineToUnload.cp.directionNode, self.combineOffset, 0, backShift)
cpDebug:drawLine(cx, cy + 1, cz, 1, 0, 0, x, y + 1, z)
else
cpDebug:drawLine(cx, cy + 1, cz, 0, 1, 0, x, y + 1, z)
end
return x, y, z, isBeside
end
function CombineUnloadAIDriver:getDrivingCoordsBehind()
local tx,ty,tz = localToWorld(self:getDirectionNode(),0,0,5)
local sideShift,_,backShift = worldToLocal(self.combineToUnload.cp.directionNode,tx,ty,tz)
local x,y,z = 0,0,0
local sx,sy,sz = getWorldTranslation(self:getDirectionNode())
local _,_,backShiftNode = worldToLocal(self.combineToUnload.cp.directionNode,sx,sy,sz)
if backShiftNode > -self:getCombinesMeasuredBackDistance() then
local lx,lz = AIVehicleUtil.getDriveDirection(self.combineToUnload.cp.directionNode, tx,ty,tz);
local cx,cy,cz = getWorldTranslation(self.combineToUnload.cp.directionNode)
local fixOffset = g_combineUnloadManager:getCombinesPipeOffset(self.combineToUnload)
if sideShift > 0 then
x,y,z = localToWorld(self.combineToUnload.cp.directionNode,fixOffset,0,backShift)
else
x,y,z = localToWorld(self.combineToUnload.cp.directionNode,-fixOffset,0,backShift)
end
cpDebug:drawLine(cx,cy+1,cz, 100, 100, 100, x,cy+1,z)
else
x,y,z = localToWorld(self.combineToUnload.cp.directionNode,0,0, - (self:getCombinesMeasuredBackDistance()))
end
--just Debug
local colliNode = self.vehicle.cp.driver.collisionDetector.trafficCollisionTriggers[1]
local sx,sy,sz = getWorldTranslation(colliNode)
cpDebug:drawLine(sx,sy,sz, 100, 100, 100, x,sy,z)
--
return x,y,z
end
function CombineUnloadAIDriver:getDrivingCoordsBehindTractor(tractorToFollow)
local sx,sy,sz = localToWorld(self:getDirectionNode(),0,0,5)
local sideShift,_,backShift = worldToLocal(tractorToFollow.cp.directionNode,sx,sy,sz)
local tx,ty,tz = localToWorld(tractorToFollow.cp.directionNode,0,0,math.max(-30,backShift))
return tx,ty,tz
end
function CombineUnloadAIDriver:getDrivingCoordsBesideTractor(tractorToFollow)
local offset = self:getChopperOffset(self.combineToUnload)
local sx,sy,sz = localToWorld(self:getDirectionNode(),0,0,5)
local sideShift,_,backShift = worldToLocal(tractorToFollow.cp.directionNode,sx,sy,sz)
local newX = 0
if offset < 0 then
newX = - 4.5
else
newX = 4.5
end
local tx,ty,tz = localToWorld(tractorToFollow.cp.directionNode,newX,0,math.max(-20,backShift))
cpDebug:drawLine(sx,sy+1,sz, 100, 100, 100, tx,ty+1,tz)
return tx,ty,tz
end
function CombineUnloadAIDriver:getColliPointHitsTheCombine()
local colliNode = self.vehicle.cp.driver.collisionDetector.trafficCollisionTriggers[1]
local cx,cy,cz = localToWorld(colliNode,-1.5,0,0)
local tx,ty,tz = localToWorld(colliNode, 1.5,0,0)
local x1,_,z1 = localToWorld(self.combineToUnload.cp.directionNode,-1.5,0,-self:getCombinesMeasuredBackDistance())
local x2,_,z2 = localToWorld(self.combineToUnload.cp.directionNode, 1.5,0,-self:getCombinesMeasuredBackDistance())
local x3,_,z3 = localToWorld(self.combineToUnload.cp.directionNode, -1.5,0,0)
return MathUtil.hasRectangleLineIntersection2D(x1,z1,x2-x1,z2-z1,x3-x1,z3-z1,cx,cz,tx-cx,tz-cz)
end
function CombineUnloadAIDriver:getZOffsetToCoordsBehind()
local colliNode = self.vehicle.cp.driver.collisionDetector.trafficCollisionTriggers[1]
local sx,sy,sz = getWorldTranslation(colliNode)
local _,_,z = worldToLocal(self.combineToUnload.cp.directionNode,sx,sy,sz)
return -(z + self:getCombinesMeasuredBackDistance())
end
function CombineUnloadAIDriver:getSpeedBesideChopper(targetNode)
local allowedToDrive = true
local baseNode = self:getPipesBaseNode(self.combineToUnload)
local bnX, bnY, bnZ = getWorldTranslation(baseNode)
--Discharge Node to AutoAimNode
local wx, wy, wz = getWorldTranslation(targetNode)
--cpDebug:drawLine(dnX,dnY,dnZ, 100, 100, 100, wx,wy,wz)
-- pipe's local position in the trailer's coordinate system
local dx,_,dz = worldToLocal(baseNode, wx, wy, wz)
--am I too far in front but beside the chopper ?
if dz < 3 and math.abs(dx)< math.abs(self:getSavedCombineOffset())+1 then
allowedToDrive = false
end
-- negative speeds are invalid
renderText(0.2,0.225,0.02,string.format("dz:%s",tostring(dz)))
return math.max(0, (self.combineToUnload.lastSpeedReal * 3600) + (MathUtil.clamp(-dz, -10, 15))), allowedToDrive
end
function CombineUnloadAIDriver:getSpeedBesideCombine(targetNode)
end
function CombineUnloadAIDriver:getSpeedBehindCombine()
if self.distanceToFront == 0 then
self:raycastFront()
return 0
else
self:raycastDistance(30)
end
local targetGap = 20
local targetDistance = self.distanceToCombine - targetGap
--renderText(0.2,0.195,0.02,string.format("self.distanceToCombine:%s, targetDistance:%s speed:%s",tostring(self.distanceToCombine),tostring(targetDistance),tostring((self.combineToUnload.lastSpeedReal * 3600) +(MathUtil.clamp(targetDistance,-10,15)))))
return (self.combineToUnload.lastSpeedReal * 3600) +(MathUtil.clamp(targetDistance,-10,15))
end
function CombineUnloadAIDriver:getSpeedBehindChopper()
local distanceToChoppersBack, _, dz = self:getDistanceFromCombine()
local fwdDistance = self.forwardLookingProximitySensorPack:getClosestObjectDistance()
if dz < 0 then
-- I'm way too forward, stop here as I'm most likely beside the chopper, let it pass before
-- moving to the middle
self:setSpeed(0)
end
local errorSafety = self.safetyDistanceFromChopper - fwdDistance
local errorTarget = self.targetDistanceBehindChopper - dz
local error = math.abs(errorSafety) < math.abs(errorTarget) and errorSafety or errorTarget
local deltaV = MathUtil.clamp(-error * 2, -10, 15)
local speed = (self.combineToUnload.lastSpeedReal * 3600) + deltaV
self:renderText(0, 0.7, 'd = %.1f, dz = %.1f, speed = %.1f, errSafety = %.1f, errTarget = %.1f',
distanceToChoppersBack, dz, speed, errorSafety, errorTarget)
return speed
end
function CombineUnloadAIDriver:getOffsetBehindChopper()
local distanceToChoppersBack, dx, dz = self:getDistanceFromCombine()
local rightDistance = self.forwardLookingProximitySensorPack:getClosestObjectDistance(-90)
local fwdRightDistance = self.forwardLookingProximitySensorPack:getClosestObjectDistance(-45)
local minDistance = math.min(rightDistance, fwdRightDistance / 1.4)
local currentOffsetX, _ = self.followCourse:getOffset()
-- TODO: course offset seems to be inverted
currentOffsetX = - currentOffsetX
local error
if dz < 0 and minDistance < 1000 then
-- proximity sensor in range, use that to adjust our target offset
-- TODO: use actual vehicle width instead of magic constant (we need to consider vehicle width
-- as the proximity sensor is in the middle
error = (self.safetyDistanceFromChopper + 1) - minDistance
self.targetOffsetBehindChopper = MathUtil.clamp(self.targetOffsetBehindChopper + 0.02 * error, -20, 20)
self:debug('err %.1f target %.1f', error, self.targetOffsetBehindChopper)
end
error = self.targetOffsetBehindChopper - currentOffsetX
local newOffset = currentOffsetX + error * 0.2
self:renderText(0, 0.68, 'right = %.1f, fwdRight = %.1f, current = %.1f, err = %1.f',
rightDistance, fwdRightDistance, currentOffsetX, error)
self:debug('right = %.1f, fwdRight = %.1f, current = %.1f, err = %1.f',
rightDistance, fwdRightDistance, currentOffsetX, error)
return MathUtil.clamp(-newOffset, -50, 50)
end
function CombineUnloadAIDriver:getSpeedBehindTractor(tractorToFollow)
local targetDistance = 35
local diff = courseplay:distanceToObject(self.vehicle, tractorToFollow) - targetDistance
return math.min(self.vehicle.cp.speeds.field,(tractorToFollow.lastSpeedReal*3600) +(MathUtil.clamp( diff,-10,25)))
end
function CombineUnloadAIDriver:getPipesBaseNode(combine)
return g_combineUnloadManager:getPipesBaseNode(combine)
end
function CombineUnloadAIDriver:getCombineIsTurning()
return self.combineToUnload.cp.driver and self.combineToUnload.cp.driver:isTurning()
end
function CombineUnloadAIDriver:getCombineOffset(combine)
return g_combineUnloadManager:getCombinesPipeOffset(combine)
end
function CombineUnloadAIDriver:getChopperOffset(combine)
local pipeOffset = g_combineUnloadManager:getCombinesPipeOffset(combine)
local leftOk, rightOk = g_combineUnloadManager:getPossibleSidesToDrive(combine)
local currentOffset = self.combineOffset
local newOffset = currentOffset
-- fruit on both sides, stay behind the chopper
if not leftOk and not rightOk then
newOffset = 0
elseif leftOk and not rightOk then
-- no fruit to the left
if currentOffset >= 0 then
-- we are already on the left or middle, go to left
newOffset = pipeOffset
else
-- we are on the right, move to the middle
newOffset = 0
end
elseif not leftOk and rightOk then
-- no fruit to the right
if currentOffset <= 0 then
-- we are already on the right or in the middle, move to the right
newOffset = -pipeOffset