forked from Courseplay/courseplay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
turn.lua
2755 lines (2387 loc) · 138 KB
/
turn.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
local abs, min, max, floor, ceil, square, pi, rad, deg = math.abs, math.min, math.max, math.floor, math.ceil, math.sqrt, math.pi, math.rad, math.deg;
local _; --- The _ is an discard character for values not needed. Setting it to local, prevent's it from being an global variable.
--- SET VALUES
local wpDistance = 1.5; -- Waypoint Distance in Straight lines
local wpCircleDistance = 1; -- Waypoint Distance in circles
-- if the direction difference between turnStart and turnEnd is bigger than this then
-- we consider that as a turn when switching to the next up/down lane and assume that
-- after the turn we'll be heading into the opposite direction.
local laneTurnAngleThreshold = 150
---@param turnContext TurnContext
function courseplay:turn(vehicle, dt, turnContext)
---- TURN STAGES:
-- 0: Raise implements
-- 1: Create Turn maneuver (Creating waypoints to follow)
-- 2: Drive Turn maneuver
-- abort turn if loaded and heading back to the silo except when on an alignment course
-- (which is a turn manever) to the first course waypoint
if vehicle.cp.isLoaded and not courseplay:onAlignmentCourse( vehicle ) then
vehicle.cp.isTurning = nil;
courseplay:clearTurnTargets(vehicle);
return;
end
-- TODO: move this to TurnContext?
local realDirectionNode = AIDriverUtil.getDirectionNode(vehicle)
local allowedToDrive = true;
local moveForwards = true;
local refSpeed = vehicle.cp.speeds.turn;
local directionForce = 1;
local lx, lz = 0, 1;
local dtpX, dtpZ = 0, 1;
local turnOutTimer = 1500;
local turnTimer = 1500;
local wpChangeDistance = 3;
local reverseWPChangeDistance = 5;
local reverseWPChangeDistanceWithTool = 3;
local isHarvester = Utils.getNoNil(courseplay:isCombine(vehicle) or courseplay:isChopper(vehicle) or courseplay:isHarvesterSteerable(vehicle), false);
local allowedAngle = vehicle.cp.changeDirAngle or isHarvester and 15 or 3; -- Used for changing direction if the vehicle or vehicle and tool angle difference are below that.
if vehicle.cp.noStopOnEdge then
turnOutTimer = 0;
end;
--- This is in case we use manually recorded fieldswork course and not generated.
if not vehicle.cp.courseWorkWidth then
courseplay:calculateWorkWidth(vehicle, true);
vehicle.cp.courseWorkWidth = vehicle.cp.workWidth;
end;
-- This is to correct course work width when loading from a save course when using multiTools
if vehicle.cp.multiTools and vehicle.cp.multiTools > 1 and vehicle.cp.courseWorkWidth ~= vehicle.cp.workWidth*vehicle.cp.multiTools then
vehicle.cp.courseWorkWidth = vehicle.cp.workWidth*vehicle.cp.multiTools
end;
-- find out the headland height to figure out if we have enough room on the headland to make turns
if vehicle.cp.courseWorkWidth and vehicle.cp.courseWorkWidth > 0 and vehicle.cp.courseNumHeadlandLanes and vehicle.cp.courseNumHeadlandLanes > 0 then
-- First headland is only half the work width
vehicle.cp.headlandHeight = vehicle.cp.courseWorkWidth / 2;
-- Add extra workwidth for each extra headland
if vehicle.cp.courseNumHeadlandLanes > 1 then
vehicle.cp.headlandHeight = vehicle.cp.headlandHeight + ((vehicle.cp.courseNumHeadlandLanes - 1) * vehicle.cp.courseWorkWidth);
end;
else
vehicle.cp.headlandHeight = 0;
end;
--- Get front and back markers
local frontMarker = Utils.getNoNil(vehicle.cp.aiFrontMarker, -3);
local backMarker = Utils.getNoNil(vehicle.cp.backMarkerOffset,0);
local vehicleX, vehicleY, vehicleZ = getWorldTranslation(realDirectionNode);
----------------------------------------------------------
-- Debug prints
----------------------------------------------------------
if courseplay.debugChannels[14] then
if #vehicle.cp.turnTargets > 0 then
-- Draw debug points for waypoints.
for index, turnTarget in ipairs(vehicle.cp.turnTargets) do
if index < #vehicle.cp.turnTargets then
local nextTurnTarget = vehicle.cp.turnTargets[index + 1];
local posY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, turnTarget.posX, 300, turnTarget.posZ);
local nextPosY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, nextTurnTarget.posX, 300, nextTurnTarget.posZ);
if turnTarget.turnReverse then
local color = { r = 0, g = 1, b = 0}; -- Green Line
--if not nextTurnTarget.turnReverse then
-- color["r"], color["g"], color["b"] = 0, 1, 1; -- Light Blue Line
--end
cpDebug:drawLine(turnTarget.posX, posY + 3, turnTarget.posZ, color["r"], color["g"], color["b"], nextTurnTarget.posX, nextPosY + 3, nextTurnTarget.posZ); -- Green Line
if turnTarget.revPosX and turnTarget.revPosZ then
nextPosY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, turnTarget.revPosX, 300, turnTarget.revPosZ);
cpDebug:drawLine(turnTarget.posX, posY + 3, turnTarget.posZ, 1, 0, 0, turnTarget.revPosX, nextPosY + 3, turnTarget.revPosZ); -- Red Line
end;
else
local color = { r = 0, g = 1, b = 1}; -- Light Blue Line
if nextTurnTarget.changeDirectionWhenAligned then
color["r"], color["g"], color["b"] = 1, 0.706, 0; -- Orange Line
end
cpDebug:drawLine(turnTarget.posX, posY + 3, turnTarget.posZ, color["r"], color["g"], color["b"], nextTurnTarget.posX, nextPosY + 3, nextTurnTarget.posZ); -- Light Blue Line
end;
elseif turnTarget.turnReverse and turnTarget.revPosX and turnTarget.revPosZ then
local posY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, turnTarget.posX, 300, turnTarget.posZ);
local nextPosY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, turnTarget.revPosX, 300, turnTarget.revPosZ);
cpDebug:drawLine(turnTarget.posX, posY + 3, turnTarget.posZ, 1, 0, 0, turnTarget.revPosX, nextPosY + 3, turnTarget.revPosZ); -- Red Line
end;
end;
end;
if turnContext and turnContext.turnStartWpNode and turnContext.turnEndWpNode then
DebugUtil.drawDebugNode(turnContext.turnStartWpNode.node, 'Start')
DebugUtil.drawDebugNode(turnContext.turnEndWpNode.node, 'End')
end
end;
--- Get the directionNodeToTurnNodeLength used for reverse turn distances
-- this is the distance between the tractor's directionNode and the real turning node of the implement (?)
local directionNodeToTurnNodeLength = courseplay:getDirectionNodeToTurnNodeLength(vehicle);
--- Get the firstReverseWheledWorkTool used for reversing
local reversingWorkTool = courseplay:getFirstReversingWheeledWorkTool(vehicle);
--- Reset reverseWPChangeDistance if we don't have an trailed implement
if reversingWorkTool then
reverseWPChangeDistance = reverseWPChangeDistanceWithTool;
end;
--- While driving (Stage 2 & 3), do we need to use the reversing WP change distance
local curTurnTarget = vehicle.cp.turnTargets[vehicle.cp.curTurnIndex];
if curTurnTarget and curTurnTarget.turnReverse then
wpChangeDistance = reverseWPChangeDistance;
end;
----------------------------------------------------------
-- TURN STAGES 1 - 3
----------------------------------------------------------
if vehicle.cp.turnStage > 0 then
----------------------------------------------------------
-- TURN STAGES 1 - Create Turn maneuver (Creating waypoints to follow)
----------------------------------------------------------
if vehicle.cp.turnStage == 1 then
--- Cleanup in case we already have old info
courseplay:clearTurnTargets(vehicle); -- Make sure we have cleaned it from any previus usage.
--- Setting default turnInfo values
local turnInfo = {};
turnInfo.directionNode = realDirectionNode
turnInfo.frontMarker = frontMarker;
turnInfo.backMarker = backMarker;
turnInfo.halfVehicleWidth = 2.5;
turnInfo.directionNodeToTurnNodeLength = directionNodeToTurnNodeLength + 0.5; -- 0.5 is to make the start turn point just a tiny in front of the tractor
-- when PPC is driving we don't have to care about wp change distances, PPC takes care of that. Still use
-- a small value to make sure none of the turn generator functions end up with overlapping waypoints
turnInfo.wpChangeDistance = 0.5
turnInfo.reverseWPChangeDistance = 0.5
turnInfo.direction = -1;
turnInfo.haveHeadlands = courseplay:haveHeadlands(vehicle);
-- Headland height in the waypoint overrides the generic headland height calculation. This is for the
-- short edge headlands where we make 180 turns on te headland course. The generic calculation would use
-- the number of headlands and think there is room on the headland to make the turn.
-- Therefore, the course generator will add a headlandHeightForTurn = 0 for these turn waypoints to make
-- sure on field turns are calculated correctly.
turnInfo.headlandHeight = turnContext.turnStartWp.headlandHeightForTurn and
turnContext.turnStartWp.headlandHeightForTurn or vehicle.cp.headlandHeight;
turnInfo.numLanes ,turnInfo.onLaneNum = courseplay:getLaneInfo(vehicle);
turnInfo.turnOnField = vehicle.cp.turnOnField;
turnInfo.reverseOffset = 0;
turnInfo.extraAlignLength = 6;
turnInfo.haveWheeledImplement = reversingWorkTool ~= nil;
if turnInfo.haveWheeledImplement then
turnInfo.reversingWorkTool = reversingWorkTool;
turnInfo.extraAlignLength = turnInfo.extraAlignLength + directionNodeToTurnNodeLength * 2;
end;
turnInfo.isHarvester = isHarvester;
-- headland turn data
vehicle.cp.headlandTurn = turnContext:isHeadlandCorner() and {} or nil
-- direction halfway between dir of turnStart and turnEnd
turnInfo.halfAngle = math.deg( getAverageAngle( math.rad( turnContext.turnEndWp.angle ),
math.rad( turnContext.turnStartWp.angle )))
-- delta between turn start and turn end
turnInfo.deltaAngle = math.pi - ( math.rad( turnContext.turnEndWp.angle )
- math.rad( turnContext.turnStartWp.angle ))
turnInfo.startDirection = turnContext.turnStartWp.angle
--- Get the turn radius either by the automatic or user provided turn circle.
local extRadius = 0.5 + (0.15 * directionNodeToTurnNodeLength); -- The extra calculation is for dynamic trailer length to prevent jackknifing;
turnInfo.turnRadius = vehicle.cp.turnDiameter * 0.5 + extRadius;
turnInfo.turnDiameter = turnInfo.turnRadius * 2;
--- Get the new turn target with offset
if courseplay:getIsVehicleOffsetValid(vehicle) and turnContext:isHeadlandCorner() == false then
courseplay:debug(string.format("%s:(Turn) turnWithOffset = true", nameNum(vehicle)), 14);
courseplay:turnWithOffset(vehicle);
end;
local totalOffsetX = vehicle.cp.totalOffsetX * -1
--- Create temp target node and translate it.
turnInfo.targetNode = createTransformGroup("cpTempTargetNode");
link(g_currentMission.terrainRootNode, turnInfo.targetNode);
local cx,cz = turnContext.turnEndWp.x, turnContext.turnEndWp.z
local cy = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, cx, 300, cz);
setTranslation(turnInfo.targetNode, cx, cy, cz);
turnContext:setTargetNode(targetNode)
-- Rotate it's direction to the next wp.
local yRot = MathUtil.getYRotationFromDirection(turnContext.turnEndWp.dx, turnContext.turnEndWp.dz);
setRotation(turnInfo.targetNode, 0, yRot, 0);
-- Retranslate it again to the correct position if there is offsets.
if totalOffsetX ~= 0 then
local totalOffsetZ
if vehicle.cp.headlandTurn then
-- headland turns are not near 180 degrees so just moving the target left/right won't work.
-- we must move it back as well
totalOffsetZ = totalOffsetX / math.tan( turnInfo.deltaAngle / 2 )
else
totalOffsetZ = 0
end
cx, cy, cz = localToWorld( turnInfo.targetNode, totalOffsetX, 0, totalOffsetZ )
setTranslation(turnInfo.targetNode, cx, cy, cz);
courseplay:debug(("%s:(Turn) Offset x = %.1f, z = %.1f"):format( nameNum( vehicle ), totalOffsetX, totalOffsetZ ), 14 )
end;
--- Debug Print
if courseplay.debugChannels[14] then
local x,y,z = getWorldTranslation(turnInfo.targetNode);
local ctx,_,ctz = localToWorld(turnInfo.targetNode, 0, 0, 20);
--drawDebugLine(x, y+5, z, 1, 0, 0, ctx, y+5, ctz, 0, 1, 0);
cpDebug:drawLine(x, y+5, z, 1, 0, 0, ctx, y+5, ctz);
-- this is an test
courseplay:debug(("%s:(Turn) wp%d=%.1f°, wp%d=%.1f°, directionChangeDeg = %.1f° halfAngle = %.1f"):format(nameNum(vehicle),
turnContext.beforeTurnStartWp.cpIndex, turnContext.beforeTurnStartWp.angle, turnContext.turnEndWp.cpIndex, turnContext.turnEndWp.angle, turnContext.directionChangeDeg, turnInfo.halfAngle), 14);
end;
--- Get the local delta distances from the tractor to the targetNode
turnInfo.targetDeltaX, _, turnInfo.targetDeltaZ = worldToLocal(turnInfo.directionNode, cx, vehicleY, cz);
courseplay:debug(string.format("%s:(Turn) targetDeltaX=%.2f, targetDeltaZ=%.2f", nameNum(vehicle), turnInfo.targetDeltaX, turnInfo.targetDeltaZ), 14);
--- Get the turn direction
if turnContext:isHeadlandCorner() then
-- headland corner turns have a targetDeltaX around 0 so use the direction diff
if turnContext.directionChangeDeg > 0 then
turnInfo.direction = 1;
end
else
if turnInfo.targetDeltaX > 0 then
turnInfo.direction = 1;
end;
end
--- Check if tool width will collide on turn (Value is set in askForSpecialSettings)
for i=1, #(vehicle.cp.workTools) do
local workTool = vehicle.cp.workTools[i];
if workTool.cp.widthWillCollideOnTurn and vehicle.cp.courseWorkWidth and (vehicle.cp.workWidth / 2) > turnInfo.halfVehicleWidth then
turnInfo.halfVehicleWidth = vehicle.cp.workWidth / 2;
end;
end
-- Relative position of the turn start waypoint from the vehicle.
-- Note that as we start the turn when the backMarkerOffset reaches the turn start point, this zOffset
-- is the same as the backMarkerOffset
_, _, turnInfo.zOffset = worldToLocal(turnInfo.directionNode, turnContext.turnStartWp.x, vehicleY, turnContext.turnStartWp.z);
-- remember this as we'll need it later
turnInfo.deltaZBetweenVehicleAndTarget = turnInfo.targetDeltaZ
-- targetDeltaZ is now the delta Z between the turn start and turn end waypoints.
turnInfo.targetDeltaZ = turnInfo.targetDeltaZ - turnInfo.zOffset;
-- Calculate reverseOffset in case we need to reverse.
-- This is used in both wide turns and in the question mark turn
local offset = turnInfo.zOffset;
-- only if all implements are in the front
if turnInfo.frontMarker > 0 and turnInfo.backMarker > 0 then
offset = -turnInfo.zOffset - turnInfo.frontMarker;
end;
if turnInfo.turnOnField and not turnInfo.isHarvester and not vehicle.cp.aiTurnNoBackward then
turnInfo.reverseOffset = max((turnInfo.turnRadius + turnInfo.halfVehicleWidth - turnInfo.headlandHeight), offset);
elseif turnInfo.isHarvester and turnInfo.frontMarker > 0 then
-- without fully understanding this reverseOffset, correct it for combines so they don't make
-- unnecessarily wide turns (and hit trees outside the field)
turnInfo.reverseOffset = -turnInfo.frontMarker
else
-- the weird thing about this is that reverseOffset here equals to zOffset and this is why
-- the wide turn works at all, even if there's no reversing.
turnInfo.reverseOffset = offset;
end;
courseplay:debug(("%s:(Turn Data) frontMarker=%q, backMarker=%q, halfVehicleWidth=%q, directionNodeToTurnNodeLength=%q, wpChangeDistance=%q"):format(nameNum(vehicle), tostring(turnInfo.frontMarker), tostring(backMarker), tostring(turnInfo.halfVehicleWidth), tostring(turnInfo.directionNodeToTurnNodeLength), tostring(turnInfo.wpChangeDistance)), 14);
courseplay:debug(("%s:(Turn Data) reverseWPChangeDistance=%q, direction=%q, haveHeadlands=%q, headlandHeight=%q"):format(nameNum(vehicle), tostring(turnInfo.reverseWPChangeDistance), tostring(turnInfo.direction), tostring(turnInfo.haveHeadlands), tostring(turnInfo.headlandHeight)), 14);
courseplay:debug(("%s:(Turn Data) numLanes=%q, onLaneNum=%q, turnOnField=%q, reverseOffset=%q"):format(nameNum(vehicle), tostring(turnInfo.numLanes), tostring(turnInfo.onLaneNum), tostring(turnInfo.turnOnField), tostring(turnInfo.reverseOffset)), 14);
courseplay:debug(("%s:(Turn Data) haveWheeledImplement=%q, reversingWorkTool=%q, turnRadius=%q, turnDiameter=%q"):format(nameNum(vehicle), tostring(turnInfo.haveWheeledImplement), tostring(turnInfo.reversingWorkTool), tostring(turnInfo.turnRadius), tostring(turnInfo.turnDiameter)), 14);
courseplay:debug(("%s:(Turn Data) targetNode=%q, targetDeltaX=%q, targetDeltaZ=%q, zOffset=%q"):format(nameNum(vehicle), tostring(turnInfo.targetNode), tostring(turnInfo.targetDeltaX), tostring(turnInfo.targetDeltaZ), tostring(turnInfo.zOffset)), 14);
courseplay:debug(("%s:(Turn Data) reverseOffset=%q, isHarvester=%q"):format(nameNum(vehicle), tostring(turnInfo.reverseOffset), tostring(turnInfo.isHarvester)), 14);
if not turnContext:isHeadlandCorner() then
----------------------------------------------------------
-- SWITCH TO THE NEXT LANE
----------------------------------------------------------
courseplay:debug(string.format("%s:(Turn) Direction difference is %.1f, this is a lane switch.", nameNum(vehicle), turnContext.directionChangeDeg), 14);
----------------------------------------------------------
-- WIDE TURNS (Turns where the distance to next lane is bigger than the turning Diameter)
----------------------------------------------------------
if abs(turnInfo.targetDeltaX) >= turnInfo.turnDiameter then
if abs(turnInfo.targetDeltaX) >= (turnInfo.turnDiameter * 2) and abs(turnInfo.targetDeltaZ) >= (turnInfo.turnRadius * 3) then
courseplay:generateTurnTypeWideTurnWithAvoidance(vehicle, turnInfo);
else
courseplay:generateTurnTypeWideTurn(vehicle, turnInfo);
end
----------------------------------------------------------
-- NAROW TURNS (Turns where the distance to next lane is smaller than the turning Diameter)
----------------------------------------------------------
else
--- If we have wheeled implement, then do turns based on that.
if turnInfo.haveWheeledImplement then
--- Get the Triangle sides
local centerOffset = abs(turnInfo.targetDeltaX) / 2;
local sideC = turnInfo.turnDiameter;
local sideB = centerOffset + turnInfo.turnRadius;
local centerHeight = square(sideC^2 - sideB^2);
--- Check if there is enough space to make Ohm turn on the headland.
local useOhmTurn = false;
if (-turnInfo.zOffset + centerHeight + turnInfo.turnRadius + turnInfo.halfVehicleWidth) < turnInfo.headlandHeight then
useOhmTurn = true;
end;
--- Ohm Turn
if useOhmTurn or turnInfo.isHarvester or vehicle.cp.aiTurnNoBackward or not turnInfo.turnOnField then
courseplay:generateTurnTypeOhmTurn(vehicle, turnInfo);
else
--- Questionmark Turn
courseplay:generateTurnTypeQuestionmarkTurn(vehicle, turnInfo);
end;
--- If not wheeled implement, then do the short turns.
else
--- Get the Triangle sides
turnInfo.centerOffset = (turnInfo.targetDeltaX * turnInfo.direction) - turnInfo.turnRadius;
local sideC = turnInfo.turnDiameter;
local sideB = turnInfo.turnRadius + turnInfo.centerOffset; -- which is exactly targetDeltaX, see above
turnInfo.centerHeight = square(sideC^2 - sideB^2);
local neededSpace = abs(turnInfo.targetDeltaZ) + turnInfo.zOffset + 1 + turnInfo.centerHeight + (turnInfo.reverseWPChangeDistance * 1.5);
--- Forward 3 Point Turn
if neededSpace < turnInfo.headlandHeight or turnInfo.isHarvester or not turnInfo.turnOnField then
courseplay:generateTurnTypeForward3PointTurn(vehicle, turnInfo);
--- Reverse 3 Point Turn
else
courseplay:generateTurnTypeReverse3PointTurn(vehicle, turnInfo);
end;
end;
end
else
-------------------------------------------------------------
-- A SHARP TURN, LIKELY ON THE HEADLAND BUT NOT A LANE SWITCH
-------------------------------------------------------------
courseplay:debug(string.format("%s:(Turn) Direction difference is %.1f, this is a corner, maneuver type = %d.",
nameNum(vehicle), turnContext.directionChangeDeg, vehicle.cp.headland.reverseManeuverType), 14);
vehicle.cp.turnCorner = turnContext:createCorner(vehicle, turnInfo.turnRadius)
courseplay.generateTurnTypeHeadlandCornerReverseStraightTractor(vehicle, turnInfo)
end
cpPrintLine(14, 1);
courseplay:debug(string.format("%s:(Turn) Generated %d Turn Waypoints", nameNum(vehicle), #vehicle.cp.turnTargets), 14);
cpPrintLine(14, 3);
vehicle.cp.turnStage = 2;
--vehicle.cp.turnStage = 100; -- Stop the tractor (Developing Tests)
unlink(turnInfo.targetNode);
delete(turnInfo.targetNode);
----------------------------------------------------------
-- TURN STAGES 2 - Drive Turn maneuver
----------------------------------------------------------
elseif vehicle.cp.turnStage == 2 then
if curTurnTarget then
if curTurnTarget.turnEnd then
if vehicle.cp.curTurnIndex == #vehicle.cp.turnTargets then
-- We are on the last waypoint, so we goto stage 3 without changing to new waypoints.
vehicle.cp.turnStage = 3;
else
-- We have more waypoints, so we goto stage 4, which will still change waypoints together with checking if we can lower the implement
vehicle.cp.turnStage = 4;
end;
courseplay:debug(string.format("%s:(Turn) Ending turn at waypoint %d, switch to stage %d", nameNum(vehicle), vehicle.cp.curTurnIndex, vehicle.cp.turnStage ), 14);
return;
end;
local dist = courseplay:distance(curTurnTarget.posX, curTurnTarget.posZ, vehicleX, vehicleZ);
local distOrig = dist
local forceSwitch = false
-- Set reversing settings.
if curTurnTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
if reversingWorkTool and reversingWorkTool.cp.realTurningNode then
local workToolX, workToolY, workToolZ = getWorldTranslation(reversingWorkTool.cp.realTurningNode);
dist = courseplay:distance(curTurnTarget.posX, curTurnTarget.posZ, workToolX, workToolZ);
local _, _, dz = worldToLocal(reversingWorkTool.cp.realTurningNode, curTurnTarget.posX, workToolY, curTurnTarget.posZ)
if dz > 0 then
-- we are reversing but the target is in front of us, switch to the next target to avoid
-- circling back to this one
forceSwitch = true
courseplay.debugVehicle(14, vehicle, '(Turn) Reversing with tool but target %d is in front of us, dist = %.1f, dz = %.1f',
vehicle.cp.curTurnIndex, dist, dz)
end
if courseplay.debugChannels[14] then
cpDebug:drawLine(vehicleX, workToolY + 5, vehicleZ, 1, 1, 0, workToolX, workToolY + 5, workToolZ);
end
end;
-- If next wp is more than 10 meters ahead, use fieldwork speed.
elseif dist > 10 and not curTurnTarget.turnReverse then
refSpeed = vehicle.cp.speeds.field;
end;
-- Change turn waypoint
if dist < wpChangeDistance or forceSwitch then
-- raise turn progress events to turn plows
local progress = vehicle.cp.curTurnIndex / #vehicle.cp.turnTargets
if turnContext then
vehicle:raiseAIEvent("onAITurnProgress", "onAIImplementTurnProgress", progress, turnContext:isLeftTurn())
end
courseplay:debug( string.format( "%s:(Turn) @( %.1f, %.1f) ix = %d/%d, distOrig = %.1f, dist = %.1f, wpChangeDistance = %.1f, progress = %.0f",
nameNum( vehicle ), vehicleX, vehicleZ, vehicle.cp.curTurnIndex, #vehicle.cp.turnTargets, distOrig, dist, wpChangeDistance, progress * 100 ), 14)
-- See if we have to raise/lower implements at this point
if vehicle.cp.turnTargets[vehicle.cp.curTurnIndex].raiseImplement then
courseplay:debug( string.format( "%s:(Turn) raising implement at turn waypoint %d", nameNum(vehicle), vehicle.cp.curTurnIndex ), 14 )
vehicle.cp.driver:raiseImplements()
elseif vehicle.cp.turnTargets[vehicle.cp.curTurnIndex].lowerImplement then
courseplay:debug( string.format( "%s:(Turn) lowering implement at turn waypoint %d", nameNum(vehicle), vehicle.cp.curTurnIndex ), 14 )
vehicle.cp.driver:lowerImplements()
end
local nextCurTurnIndex = min(vehicle.cp.curTurnIndex + 1, #vehicle.cp.turnTargets);
local changeDir = ((curTurnTarget.turnReverse and not vehicle.cp.turnTargets[nextCurTurnIndex].turnReverse) or (not curTurnTarget.turnReverse and vehicle.cp.turnTargets[nextCurTurnIndex].turnReverse))
-- We are still moving and want to switch directions STOP if using MR mod. And we haven't yet stopped
if math.abs(vehicle.lastSpeedReal) > 0.0001 and vehicle.mrIsMrVehicle and changeDir and not vehicle.cp.mrHasStopped then
allowedToDrive = false
-- We have finally stopped on direction. Set a flag to allow movement again
elseif math.abs(vehicle.lastSpeedReal) < 0.0001 and vehicle.mrIsMrVehicle and changeDir then
vehicle.cp.mrHasStopped = true;
else
-- We are now 1 index away from the direction clear the flag
if vehicle.cp.mrHasStopped then
vehicle.cp.mrHasStopped = nil
end;
vehicle.cp.curTurnIndex = nextCurTurnIndex;
end
end;
-- Start reversing before time if we are allowed and if we can
if curTurnTarget.changeDirectionWhenAligned then
-- Get the world rotation of the next lane
local laneRot = MathUtil.getYRotationFromDirection(turnContext.turnEndWp.dx, turnContext.turnEndWp.dz);
laneRot = deg(laneRot);
if reversingWorkTool and reversingWorkTool.cp.realTurningNode then
-- Get the world rotation of the tool
dx, _, dz = localDirectionToWorld(reversingWorkTool.cp.realTurningNode, 0, 0, 1);
else
-- Get the world rotation of the vehicle
dx, _, dz = localDirectionToWorld(realDirectionNode, 0, 0, 1);
end;
local toolRot = MathUtil.getYRotationFromDirection(dx, dz);
toolRot = deg(toolRot);
--courseplay:debug(("%s:(Turn) laneRot=%.2f, toolRot=%.2f"):format(nameNum(vehicle), laneRot, toolRot), 14);
-- Get the angle difference
local angleDifference = min( abs((toolRot + 180 - laneRot) %360 - 180), abs((laneRot + 180 - toolRot) %360 - 180) )
-- If the angle diff is less than the allowed angle, then goto the first wp in opposite drive direction
if angleDifference then
courseplay:debug(("%s:(Turn) Change direction when anglediff(%.2f) <= %.2f"):format(nameNum(vehicle), angleDifference, allowedAngle), 14);
if angleDifference <= allowedAngle then
if math.abs(vehicle.lastSpeedReal) > 0.0001 and vehicle.mrIsMrVehicle then
allowedToDrive = false -- This is to ensure MR brakes before changing directions to prevent runaway tractors on steep grades
else
local changeToForward = curTurnTarget.turnReverse;
for i = vehicle.cp.curTurnIndex, #vehicle.cp.turnTargets, 1 do
if changeToForward and not vehicle.cp.turnTargets[i].turnReverse then
courseplay:debug(("%s:(Turn) Changing to forward"):format(nameNum(vehicle)), 14);
vehicle.cp.curTurnIndex = i;
return;
elseif not changeToForward and vehicle.cp.turnTargets[i].turnReverse then
courseplay:debug(("%s:(Turn) Changing to reverse"):format(nameNum(vehicle)), 14);
vehicle.cp.curTurnIndex = i;
return;
end;
end;
end;
end;
end;
end;
else
vehicle.cp.turnStage = 1; -- (THIS SHOULD NEVER HAPPEN) Somehow we don't have any waypoints, so try recollect them.
return;
end;
----------------------------------------------------------
-- TURN STAGES 3 - Lower implement and continue on next lane
----------------------------------------------------------
elseif vehicle.cp.turnStage == 3 then
local deltaZ, lowerImplements
if courseplay:onAlignmentCourse( vehicle ) then
courseplay:endAlignmentCourse( vehicle )
courseplay:setWaypointIndex(vehicle, vehicle.cp.waypointIndex );
return
else
_, _, deltaZ = worldToLocal(realDirectionNode,turnContext.turnEndWp.x, vehicleY, turnContext.turnEndWp.z)
lowerImplements = deltaZ < frontMarker + 3
end
if curTurnTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
lowerImplements = deltaZ > frontMarker;
end;
-- Lower implement and continue on next lane
if vehicle.cp.driver:shouldLowerImplements(turnContext.turnEndWpNode.node, curTurnTarget.turnReverse) then
courseplay.debugVehicle(12, vehicle, '(Turn) lowering implements')
vehicle.cp.driver:lowerImplements()
vehicle.cp.isTurning = nil;
if vehicle.cp.driver then
vehicle.cp.driver:onTurnEnd()
end
courseplay:clearTurnTargets(vehicle);
return;
end;
----------------------------------------------------------
-- TURN STAGES 4 - Lower implement and continue on next lane (Multi waypoint version)
----------------------------------------------------------
elseif vehicle.cp.turnStage == 4 then
if curTurnTarget.turnEnd and vehicle.cp.curTurnIndex == #vehicle.cp.turnTargets then
vehicle.cp.turnStage = 3;
return;
end;
local dist = courseplay:distance(curTurnTarget.posX, curTurnTarget.posZ, vehicleX, vehicleZ);
-- Set reversing settings.
if curTurnTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
if reversingWorkTool and reversingWorkTool.cp.realTurningNode then
local workToolX, _, workToolZ = getWorldTranslation(reversingWorkTool.cp.realTurningNode);
dist = courseplay:distance(curTurnTarget.posX, curTurnTarget.posZ, workToolX, workToolZ);
if courseplay.debugChannels[14] then
local posY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, workToolX, 300, workToolZ);
cpDebug:drawLine(vehicleX, posY + 5, vehicleZ, 1, 1, 0, workToolX, posY + 5, workToolZ);
end
end;
end;
-- Change turn waypoint
if dist < wpChangeDistance then
vehicle.cp.curTurnIndex = min(vehicle.cp.curTurnIndex + 1, #vehicle.cp.turnTargets);
return;
end;
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-- Check if we are at the start of the lane and lower if so and continue working.
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
local _, _, deltaZ = worldToLocal(realDirectionNode, turnContext.turnEndWp.x, vehicleY, turnContext.turnEndWp.z)
--courseplay.debugVehicle(14, vehicle, 'ix=%d dz=%.1f', vehicle.cp.waypointIndex+1, deltaZ)
local lowerImplements = deltaZ < frontMarker + 3
if curTurnTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
lowerImplements = deltaZ > frontMarker;
end;
-- Lower implement and continue on next lane
if vehicle.cp.driver.shouldLowerImplements and vehicle.cp.driver:shouldLowerImplements(turnContext.turnEndWpNode.node, curTurnTarget.turnReverse) then
courseplay.debugVehicle(12, vehicle, '(Turn) lowering implements')
vehicle.cp.driver:lowerImplements()
vehicle.cp.isTurning = nil;
if vehicle.cp.driver then
vehicle.cp.driver:onTurnEnd()
end
courseplay:clearTurnTargets(vehicle);
return;
end;
----------------------------------------------------------
-- UNKNOWN TURN STAGE - Stop the vehicle from driving (Used for developing purpose)
----------------------------------------------------------
else
allowedToDrive = false;
end;
----------------------------------------------------------
-- TURN STAGES 0 - Finish lane and raise implement and change to stage 1
----------------------------------------------------------
else
--- Add WP to follow while doing last bit before raising Implement
if not curTurnTarget then
local extraForward = 0;
if backMarker < 0 then
extraForward = abs(backMarker);
end;
local cx, cz = courseplay:getVehicleOffsettedCoords(vehicle, turnContext.turnStartWp.x, turnContext.turnStartWp.z);
local posX, posZ = cx + (extraForward + 10) * turnContext.beforeTurnStartWp.dx, cz + (extraForward + 10) * turnContext.beforeTurnStartWp.dz;
courseplay:addTurnTarget(vehicle, posX, posZ);
end;
--- Use the speed limit if we are still working and turn speed is higher that the speed limit.
refSpeed = courseplay:getSpeedWithLimiter(vehicle, refSpeed);
if vehicle.cp.driver.shouldRaiseImplements and vehicle.cp.driver:shouldRaiseImplements(turnContext.workEndNode) then
-- raise implements only if this is not a headland turn; in headland
-- turns the turn waypoint attribute will control when to raise/lower implements
if not turnContext:isHeadlandCorner() then
vehicle.cp.driver:raiseImplements()
end
vehicle.cp.turnStage = 1;
end
end;
----------------------------------------------------------
--Set the driving direction
----------------------------------------------------------
if curTurnTarget then
local posX, posZ = curTurnTarget.revPosX or curTurnTarget.posX, curTurnTarget.revPosZ or curTurnTarget.posZ;
local directionNode = vehicle.aiVehicleDirectionNode or vehicle.cp.directionNode;
dtpX,_,dtpZ = worldToLocal(directionNode, posX, vehicleY, posZ);
if courseplay:isWheelloader(vehicle) then
dtpZ = dtpZ * 0.5; -- wheel loaders need to turn more
end;
--print( ("dtp %.1f, %.1f, %.1f"):format( dtpX, dtpZ, refSpeed ))
lx, lz = AIVehicleUtil.getDriveDirection(vehicle.cp.directionNode, posX, vehicleY, posZ);
if curTurnTarget.turnReverse then
lx, lz, moveForwards = courseplay:goReverse(vehicle,lx,lz);
end;
end;
----------------------------------------------------------
-- Debug prints: Show Current Waypoint
----------------------------------------------------------b
if courseplay.debugChannels[12] and curTurnTarget then
local posX, posZ = curTurnTarget.revPosX or curTurnTarget.posX, curTurnTarget.revPosZ or curTurnTarget.posZ;
local posY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, posX, 300, posZ);
cpDebug:drawLine(posX, posY + 3, posZ, 0, 0, 1, posX, posY + 4, posZ); -- Blue Line
end;
if courseplay.debugChannels[14] then
local x1, _, z1 = localToWorld( realDirectionNode, -1, 0, frontMarker )
local x2, _, z2 = localToWorld( realDirectionNode, 1, 0, frontMarker )
local y = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x1, 0, z1 );
cpDebug:drawLine(x1, y + 5, z1, 0, 1, 0, x2, y + 5, z2);
local x1, _, z1 = localToWorld( realDirectionNode, -1, 0, backMarker )
local x2, _, z2 = localToWorld( realDirectionNode, 1, 0, backMarker )
cpDebug:drawLine(x1, y + 5, z1, 1, 0, 0, x2, y + 5, z2);
end
if vehicle.cp.turnCorner then
vehicle.cp.turnCorner:drawDebug()
end
if vehicle.cp.drivingMode:get() == DrivingModeSetting.DRIVING_MODE_AIDRIVER then
-- in AIDriver based modes do not call / use legacy collision code
allowedToDrive = vehicle.cp.driver:detectCollision(dt)
else
-- allowedToDrive = courseplay:checkTraffic(self, true, allowedToDrive)
end
----------------------------------------------------------
-- allowedToDrive false -> SLOW DOWN TO STOP
----------------------------------------------------------
if not allowedToDrive then
-- reset slipping timers
courseplay:resetSlippingTimers(vehicle)
if courseplay.debugChannels[21] then
renderText(0.5,0.85-(0.03*vehicle.cp.coursePlayerNum),0.02,string.format("%s: vehicle.lastSpeedReal: %.8f km/h ",nameNum(vehicle),vehicle.lastSpeedReal*3600))
end
vehicle.cp.TrafficBrake = false;
vehicle.cp.isTrafficBraking = false;
if vehicle.cp.curSpeed > 1 then
allowedToDrive = true;
moveForwards = vehicle.movingDirection == 1;
directionForce = -1;
end;
vehicle.cp.speedDebugLine = ("turn("..tostring(debug.getinfo(1).currentline-1).."): allowedToDrive false ")
else
vehicle.cp.speedDebugLine = ("turn("..tostring(debug.getinfo(1).currentline-1).."): refSpeed = "..tostring(refSpeed))
courseplay:setSpeed(vehicle, refSpeed )
end;
----------------------------------------------------------
-- Traffic break if something is in front of us
----------------------------------------------------------
if vehicle.cp.TrafficBrake then
moveForwards = vehicle.movingDirection == -1;
end
----------------------------------------------------------
-- Vehicles with inverted driving direction.
----------------------------------------------------------
if vehicle.isReverseDriving then
lz = -lz
end
if vehicle.cp.useProgessiveBraking then
courseplay:mrProgressiveBreaking(vehicle, refSpeed)
if vehicle.cp.mrAccelrator then
directionForce = -vehicle.cp.mrAccelrator -- The progressive breaking function returns a postive number which accelerates the tractor
end
end
-- hold while straw swath is active (not during headland turn maneuvers though)
local holdInTurn = not vehicle.cp.headlandTurn and vehicle.cp.driver and vehicle.cp.driver:holdInTurnManeuver(vehicle.cp.turnStage == 0)
allowedToDrive = not holdInTurn and allowedToDrive
if curTurnTarget and ((curTurnTarget.turnReverse and reversingWorkTool ~= nil) or (courseplay:onAlignmentCourse( vehicle ) and vehicle.cp.curTurnIndex < 2 )) then
if math.abs(vehicle.lastSpeedReal) < 0.0001 and not g_currentMission.missionInfo.stopAndGoBraking then
if not moveForwards then
vehicle.nextMovingDirection = -1
else
vehicle.nextMovingDirection = 1
end
end
AIVehicleUtil.driveInDirection(vehicle, dt, vehicle.cp.steeringAngle, directionForce, 0.5, 20, allowedToDrive, moveForwards, lx, lz, refSpeed, 1);
else
dtpZ = dtpZ * 0.85;
courseplay.driveToPoint(vehicle, dt, directionForce, allowedToDrive, moveForwards, dtpX, dtpZ, refSpeed);
end
if vehicle.cp.drivingMode:get() == DrivingModeSetting.DRIVING_MODE_AIDRIVER then
-- in AIDriver based modes do not call / use legacy collision code
else
courseplay:setTrafficCollision(vehicle, lx, lz,false)
end
end;
--[[
This is a copy of the original Giants VehicleUtil.driveToPoint() with the speed adjustment removed. The original
code slows down the vehicle according to the difference between the target steering angle and the current steering
angle.
This is generally a good thing but with this old turn code we do not have a pure pursuit controller yet and
the vehicle is moving towards a fix point. This means that the steering angle is continuously changing while driving
towards this waypoint (trending towards zero as we approach it) and when switching to the next waypoint, the target
steering angle has a sudden jump, causing the speed adjustment to kick in. You can observe the changing steering angle
when looking at the vehicle's wheels while in a turn.
The speed adjustment causes a sudden slow down whenever the turn waypoint is changed, that is why we remove it here as
the turn maneuver seems to work fine without it and it is a lot smoother.
On the long term this should be solved by using the pure pursuit controller during the turns as well as the PPC has
no fixed waypoint so the steering angle remains constant and the speed adjustment won't kick in, so the original
Giants function can again be used.
--]]
function courseplay.driveToPoint(self, dt, acceleration, allowedToDrive, moveForwards, tX, tZ, maxSpeed, doNotSteer)
if self.firstTimeRun then
if allowedToDrive then
local tX_2 = tX * 0.5
local tZ_2 = tZ * 0.5
local d1X, d1Z = tZ_2, -tX_2
if tX > 0 then
d1X, d1Z = -tZ_2, tX_2
end
local hit,_,f2 = MathUtil.getLineLineIntersection2D(tX_2,tZ_2, d1X,d1Z, 0,0, tX, 0)
if doNotSteer == nil or not doNotSteer then
local rotTime = 0
if hit and math.abs(f2) < 100000 then
local radius = tX * f2
rotTime = self.wheelSteeringDuration * ( math.atan(1/radius) / math.atan(1/self.maxTurningRadius) )
end
local targetRotTime
if rotTime >= 0 then
targetRotTime = math.min(rotTime, self.maxRotTime)
else
targetRotTime = math.max(rotTime, self.minRotTime)
end
if targetRotTime > self.rotatedTime then
self.rotatedTime = math.min(self.rotatedTime + dt*self:getAISteeringSpeed(), targetRotTime)
else
self.rotatedTime = math.max(self.rotatedTime - dt*self:getAISteeringSpeed(), targetRotTime)
end
end
end
self:getMotor():setSpeedLimit(math.min(maxSpeed, self:getCruiseControlSpeed()))
if self:getCruiseControlState() ~= Drivable.CRUISECONTROL_STATE_ACTIVE then
self:setCruiseControlState(Drivable.CRUISECONTROL_STATE_ACTIVE)
end
if not allowedToDrive then
acceleration = 0
end
if not moveForwards then
acceleration = -acceleration
end
WheelsUtil.updateWheelsPhysics(self, dt, self.lastSpeedReal*self.movingDirection, acceleration, not allowedToDrive, true)
end
end
function courseplay:generateTurnTypeWideTurn(vehicle, turnInfo)
cpPrintLine(14, 3);
courseplay:debug(string.format("%s:(Turn) Using Wide Turn", nameNum(vehicle)), 14);
cpPrintLine(14, 3);
local posX, posZ;
local fromPoint, toPoint = {}, {};
local canTurnOnHeadland = false;
local center1, center2, startDir, intersect1, intersect2, stopDir = {}, {}, {}, {}, {}, {};
-- Check if we can turn on the headlands
if (-turnInfo.zOffset + turnInfo.turnRadius + turnInfo.halfVehicleWidth) <= turnInfo.headlandHeight then
canTurnOnHeadland = true;
end;
--- Get the center height offset
if not turnInfo.haveHeadlands and not turnInfo.isHarvester and not vehicle.cp.aiTurnNoBackward and turnInfo.turnOnField then
turnInfo.reverseOffset = turnInfo.reverseOffset + abs(turnInfo.targetDeltaZ * 0.75);
end;
--- Add extra length to the directionNodeToTurnNodeLength if there is an pivoted tool behind the tractor.
-- This is to prevent too sharp turning when reversing to the first reverse point.
local directionNodeToTurnNodeLength = turnInfo.directionNodeToTurnNodeLength;
if turnInfo.haveWheeledImplement and turnInfo.reversingWorkTool.cp.isPivot then
directionNodeToTurnNodeLength = directionNodeToTurnNodeLength * 1.25;
end;
--- Extra WP 1 - Reverse back so we can turn inside the field (Only if we can't turn inside the headlands)
if not canTurnOnHeadland and not turnInfo.isHarvester and not vehicle.cp.aiTurnNoBackward and turnInfo.turnOnField then
-- Reverse back
fromPoint.x, _, fromPoint.z = localToWorld(turnInfo.directionNode, 0, 0, -directionNodeToTurnNodeLength);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.directionNode, 0, 0, turnInfo.zOffset - turnInfo.reverseOffset - directionNodeToTurnNodeLength - turnInfo.reverseWPChangeDistance);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint, true, nil, turnInfo.reverseWPChangeDistance);
end;
-- Get the 2 circle center coordinate
-- I don't understand that turnInfo.zOffset here. That is our distance from the turn start WP, and with no reverseOffset it'll put the
-- circle behind us. I think this is buggy, and only works with that magic at the beginning where we end up with the reverseOffset == zOffset
center1.x,_,center1.z = localToWorld(turnInfo.directionNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset);
center2.x,_,center2.z = localToWorld(turnInfo.targetNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.reverseOffset);
-- Get the circle intersection points
intersect1.x, intersect1.z = center1.x, center1.z;
intersect2.x, intersect2.z = center2.x, center2.z;
intersect1, intersect2 = courseplay:getTurnCircleTangentIntersectionPoints(intersect1, intersect2, turnInfo.turnRadius, turnInfo.targetDeltaX > 0);
--- Set start and stop dir for first turn circle
startDir.x,_,startDir.z = localToWorld(turnInfo.directionNode, 0, 0, turnInfo.zOffset - turnInfo.reverseOffset);
stopDir.x,_,stopDir.z = localToWorld(turnInfo.targetNode, 0, 0, turnInfo.reverseOffset);
--- Generate turn circle 1
courseplay:generateTurnCircle(vehicle, center1, startDir, intersect1, turnInfo.turnRadius, turnInfo.direction, true);
--- Generate points between the 2 circles
courseplay:generateTurnStraightPoints(vehicle, intersect1, intersect2);
--- Generate turn circle 2
courseplay:generateTurnCircle(vehicle, center2, intersect2, stopDir, turnInfo.turnRadius, turnInfo.direction, true);
--- Extra WP 2 - Reverse back to field edge
if not canTurnOnHeadland and not turnInfo.isHarvester and not vehicle.cp.aiTurnNoBackward and turnInfo.turnOnField then
-- Move a bit more forward
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, 0, 0, turnInfo.reverseOffset + directionNodeToTurnNodeLength + turnInfo.extraAlignLength + turnInfo.wpChangeDistance);
courseplay:generateTurnStraightPoints(vehicle, stopDir, toPoint, nil, nil, nil, true);
-- Reverse back
if turnInfo.reverseOffset - 3 > 0 then
fromPoint.x, _, fromPoint.z = localToWorld(turnInfo.targetNode, 0, 0, turnInfo.reverseOffset - 3);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, 0, 0, 0);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint, true, true, turnInfo.frontMarker + directionNodeToTurnNodeLength + turnInfo.reverseWPChangeDistance);
else
posX, _, posZ = localToWorld(turnInfo.targetNode, 0, 0, 0);
local revPosX, _, revPosZ = localToWorld(turnInfo.targetNode, 0, 0, -(turnInfo.frontMarker + directionNodeToTurnNodeLength + turnInfo.reverseWPChangeDistance));
courseplay:addTurnTarget(vehicle, posX, posZ, true, true, revPosX, revPosZ);
end;
--- Extra WP 3 - Turn End
else
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, 0, 0, -turnInfo.reverseOffset + turnInfo.directionNodeToTurnNodeLength + 5);
courseplay:generateTurnStraightPoints(vehicle, stopDir, toPoint, nil, true);
end;
end;
function courseplay:generateTurnTypeWideTurnWithAvoidance(vehicle, turnInfo)
cpPrintLine(14, 3);
courseplay:debug(string.format("%s:(Turn) Using Wide Turn With Corner Avoidance", nameNum(vehicle)), 14);
cpPrintLine(14, 3);
local posX, posZ;
local fromPoint, toPoint = {}, {};
local canTurnOnHeadland = false;
local center, startDir, stopDir = {}, {}, {};
-- Check if we can turn on the headlands
if (-turnInfo.zOffset + turnInfo.turnRadius + turnInfo.halfVehicleWidth) < turnInfo.headlandHeight then
canTurnOnHeadland = true;
end;
--- Add extra length to the directionNodeToTurnNodeLength if there is an pivoted tool behind the tractor.
-- This is to prevent too sharp turning when reversing to the first reverse point.
local directionNodeToTurnNodeLength = turnInfo.directionNodeToTurnNodeLength;
if turnInfo.haveWheeledImplement and turnInfo.reversingWorkTool.cp.isPivot then
directionNodeToTurnNodeLength = directionNodeToTurnNodeLength * 1.25;
end;
--- Extra WP 1 - Reverse back so we can turn inside the field (Only if we can't turn inside the headlands)
if not canTurnOnHeadland and not turnInfo.isHarvester and not vehicle.cp.aiTurnNoBackward and turnInfo.turnOnField then
-- Reverse back
fromPoint.x, _, fromPoint.z = localToWorld(turnInfo.directionNode, 0, 0, -directionNodeToTurnNodeLength);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.directionNode, 0, 0, turnInfo.zOffset - turnInfo.reverseOffset - directionNodeToTurnNodeLength - turnInfo.reverseWPChangeDistance);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint, true, nil, turnInfo.reverseWPChangeDistance);-- Reverse back
end;
----------------------------------------------------------
-- If new lane is in front of us, Do the 90-90-180 turn
----------------------------------------------------------
if turnInfo.targetDeltaZ > 0 then
--- Generate the first turn circles
center.x,_,center.z = localToWorld(turnInfo.directionNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset);
startDir.x,_,startDir.z = localToWorld(turnInfo.directionNode, 0, 0, turnInfo.zOffset - turnInfo.reverseOffset);
stopDir.x,_,stopDir.z = localToWorld(turnInfo.directionNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnRadius);
courseplay:generateTurnCircle(vehicle, center, startDir, stopDir, turnInfo.turnRadius, turnInfo.direction);
--- Generate line between first and second turn circles
fromPoint.x, fromPoint.z = stopDir.x, stopDir.z
toPoint.x, _, toPoint.z = localToWorld(turnInfo.directionNode, turnInfo.targetDeltaX - turnInfo.direction * (turnInfo.turnRadius + turnInfo.turnDiameter), 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnRadius);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint);
--- Generate the second turn circles
center.x,_,center.z = localToWorld(turnInfo.directionNode, turnInfo.targetDeltaX - turnInfo.direction * (turnInfo.turnRadius + turnInfo.turnDiameter), 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnDiameter);
startDir.x, startDir.z = toPoint.x, toPoint.z;
stopDir.x,_,stopDir.z = localToWorld(turnInfo.directionNode, turnInfo.targetDeltaX - turnInfo.direction * turnInfo.turnDiameter, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnDiameter);
courseplay:generateTurnCircle(vehicle, center, startDir, stopDir, turnInfo.turnRadius, turnInfo.direction * -1);
--- Generate line between second and third turn circles
fromPoint.x, fromPoint.z = stopDir.x, stopDir.z;
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, turnInfo.turnDiameter * turnInfo.direction, 0, turnInfo.reverseOffset);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint);
--- Generate the third turn circles
center.x,_,center.z = localToWorld(turnInfo.targetNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.reverseOffset);
startDir.x,_,startDir.z = localToWorld(turnInfo.targetNode, turnInfo.turnDiameter * turnInfo.direction, 0, turnInfo.reverseOffset);
stopDir.x,_,stopDir.z = localToWorld(turnInfo.targetNode, 0, 0, turnInfo.reverseOffset);
courseplay:generateTurnCircle(vehicle, center, startDir, stopDir, turnInfo.turnRadius, turnInfo.direction, true);
----------------------------------------------------------
-- If new lane is behind us, Do the 180-90-90 turn
----------------------------------------------------------
else
--- Generate the first turn circles
center.x,_,center.z = localToWorld(turnInfo.directionNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset);
startDir.x,_,startDir.z = localToWorld(turnInfo.directionNode, 0, 0, turnInfo.zOffset - turnInfo.reverseOffset);
stopDir.x,_,stopDir.z = localToWorld(turnInfo.directionNode, turnInfo.turnDiameter * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset);
courseplay:generateTurnCircle(vehicle, center, startDir, stopDir, turnInfo.turnRadius, turnInfo.direction);
--- Generate line between first and second turn circles
fromPoint.x, fromPoint.z = stopDir.x, stopDir.z
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, turnInfo.targetDeltaX - turnInfo.direction * turnInfo.turnDiameter, 0, turnInfo.reverseOffset - turnInfo.turnDiameter);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint);
--- Generate the second turn circles
center.x,_,center.z = localToWorld(turnInfo.targetNode, turnInfo.targetDeltaX - turnInfo.direction * (turnInfo.turnRadius + turnInfo.turnDiameter), 0, turnInfo.reverseOffset - turnInfo.turnDiameter);
startDir.x, startDir.z = toPoint.x, toPoint.z;
stopDir.x,_,stopDir.z = localToWorld(turnInfo.targetNode, turnInfo.targetDeltaX - turnInfo.direction * (turnInfo.turnRadius + turnInfo.turnDiameter), 0, turnInfo.reverseOffset - turnInfo.turnRadius);
courseplay:generateTurnCircle(vehicle, center, startDir, stopDir, turnInfo.turnRadius, turnInfo.direction * -1);
--- Generate line between second and third turn circles
fromPoint.x, fromPoint.z = stopDir.x, stopDir.z
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnRadius);
courseplay:generateTurnStraightPoints(vehicle, fromPoint, toPoint);
--- Generate the third turn circles
center.x,_,center.z = localToWorld(turnInfo.targetNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.reverseOffset);
startDir.x, startDir.z = toPoint.x, toPoint.z;
stopDir.x,_,stopDir.z = localToWorld(turnInfo.targetNode, 0, 0, turnInfo.reverseOffset);
courseplay:generateTurnCircle(vehicle, center, startDir, stopDir, turnInfo.turnRadius, turnInfo.direction, true);
end;
--- Extra WP 2 - Reverse back to field edge
if not canTurnOnHeadland and not turnInfo.isHarvester and not vehicle.cp.aiTurnNoBackward and turnInfo.turnOnField then
-- Move a bit more forward
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, 0, 0, turnInfo.reverseOffset + directionNodeToTurnNodeLength + turnInfo.extraAlignLength + turnInfo.wpChangeDistance);