forked from Courseplay/courseplay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
turn.lua
2169 lines (1864 loc) · 112 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 discart 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 Strait 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 = 135
function courseplay:turn(vehicle, dt)
---- 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 manuever) to the first course waypoint
if vehicle.cp.isLoaded and not courseplay:onAlignmentCourse( vehicle ) then
vehicle.cp.isTurning = nil;
courseplay:clearTurnTargets(vehicle);
return;
end
local realDirectionNode = vehicle.isReverseDriving and vehicle.cp.reverseDrivingDirectionNode or vehicle.cp.DirectionNode;
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 = vehicle.isReverseDriving and 3 or 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 courseworkwidth 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;
--- Make sure front and back markers is calculated.
if not vehicle.cp.haveCheckedMarkersThisTurn then
vehicle.cp.aiFrontMarker = nil;
vehicle.cp.backMarkerOffset = nil;
for _,workTool in pairs(vehicle.cp.workTools) do
courseplay:setMarkers(vehicle, workTool);
end;
vehicle.cp.haveCheckedMarkersThisTurn = true;
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 > 0 then
vehicle.cp.headlandHeight = vehicle.cp.headlandHeight + ((vehicle.cp.courseNumHeadlandLanes - 1) * vehicle.cp.courseWorkWidth);
end;
else
vehicle.cp.headlandHeight = 0;
end;
local frontMarker2 = Utils.getNoNil(vehicle.cp.aiFrontMarker, -3);
local backMarker2 = Utils.getNoNil(vehicle.cp.backMarkerOffset,0);
if vehicle.cp.hasPlough and (vehicle.cp.ploughFieldEdge or math.abs(frontMarker2 - backMarker2) < vehicle.cp.headlandHeight) then
vehicle.cp.aiFrontMarker = backMarker2;
vehicle.cp.backMarkerOffset = frontMarker2
end
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
drawDebugLine(turnTarget.posX, posY + 3, turnTarget.posZ, color["r"], color["g"], color["b"], nextTurnTarget.posX, nextPosY + 3, nextTurnTarget.posZ, color["r"], color["g"], color["b"]); -- Green Line
if turnTarget.revPosX and turnTarget.revPosZ then
nextPosY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, turnTarget.revPosX, 300, turnTarget.revPosZ);
drawDebugLine(turnTarget.posX, posY + 3, turnTarget.posZ, 1, 0, 0, turnTarget.revPosX, nextPosY + 3, turnTarget.revPosZ, 1, 0, 0); -- Red Line
end;
else
local color = { r = 0, g = 1, b = 1}; -- Light Blue Line
if nextTurnTarget.changeWhenPosible then
color["r"], color["g"], color["b"] = 1, 0.706, 0; -- Orange Line
end
drawDebugLine(turnTarget.posX, posY + 3, turnTarget.posZ, color["r"], color["g"], color["b"], nextTurnTarget.posX, nextPosY + 3, nextTurnTarget.posZ, color["r"], color["g"], color["b"]); -- 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);
drawDebugLine(turnTarget.posX, posY + 3, turnTarget.posZ, 1, 0, 0, turnTarget.revPosX, nextPosY + 3, turnTarget.revPosZ, 1, 0, 0); -- Red Line
end;
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 newTarget = vehicle.cp.turnTargets[vehicle.cp.curTurnIndex];
if newTarget and newTarget.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, false); -- Make sure we have cleaned it from any previus usage.
--- Setting default turnInfo values
local turnInfo = {};
turnInfo.directionNode = realDirectionNode
turnInfo.frontMarker = frontMarker;
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
turnInfo.wpChangeDistance = wpChangeDistance;
turnInfo.reverseWPChangeDistance = reverseWPChangeDistance;
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 = vehicle.Waypoints[vehicle.cp.waypointIndex].headlandHeightForTurn and
vehicle.Waypoints[vehicle.cp.waypointIndex].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;
turnInfo.directionChangeDeg, turnInfo.isHeadlandCorner = getDirectionChangeOfTurn( vehicle )
-- headland turn data
vehicle.cp.headlandTurn = turnInfo.isHeadlandCorner and {} or nil
-- direction halfway between dir of turnStart and turnEnd
turnInfo.halfAngle = math.deg( getAverageAngle( math.rad( vehicle.Waypoints[vehicle.cp.waypointIndex + 1 ].angle ),
math.rad( vehicle.Waypoints[vehicle.cp.waypointIndex].angle )))
-- delta between turn start and turn end
turnInfo.deltaAngle = math.pi - ( math.rad( vehicle.Waypoints[vehicle.cp.waypointIndex + 1 ].angle )
- math.rad( vehicle.Waypoints[vehicle.cp.waypointIndex].angle ))
turnInfo.startDirection = vehicle.Waypoints[vehicle.cp.waypointIndex].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 turnInfo.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 = vehicle.Waypoints[vehicle.cp.waypointIndex+1].cx, vehicle.Waypoints[vehicle.cp.waypointIndex+1].cz;
local cy = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, cx, 300, cz);
setTranslation(turnInfo.targetNode, cx, cy, cz);
-- Rotate it's direction to the next wp.
local dx, dz = courseplay.generation:getPointDirection(vehicle.Waypoints[vehicle.cp.waypointIndex+1], vehicle.Waypoints[vehicle.cp.waypointIndex+2]);
local yRot = Utils.getYRotationFromDirection(dx, 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 to 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);
-- this is an test
courseplay:debug(("%s:(Turn) wp%d=%.1f°, wp%d=%.1f°, directionChangeDeg = %.1f° halfAngle = %.1f"):format(nameNum(vehicle), vehicle.cp.waypointIndex-1, vehicle.Waypoints[vehicle.cp.waypointIndex-1].angle, vehicle.cp.waypointIndex+1, vehicle.Waypoints[vehicle.cp.waypointIndex+1].angle, turnInfo.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 turnInfo.isHeadlandCorner then
-- headland corner turns have a targetDeltaX around 0 so use the direction diff
if turnInfo.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
--- Find the zOffset based on tractors current position from the start turn wp
_, _, turnInfo.zOffset = worldToLocal(turnInfo.directionNode, vehicle.Waypoints[vehicle.cp.waypointIndex].cx, vehicleY, vehicle.Waypoints[vehicle.cp.waypointIndex].cz);
-- 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;
--- Get headland height
-- 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
-- turnInfo.headlandHeight = vehicle.cp.courseWorkWidth / 2;
-- -- Add extra workwidth for each extra headland
-- if vehicle.cp.courseNumHeadlandLanes - 1 > 0 then
-- turnInfo.headlandHeight = turnInfo.headlandHeight + ((vehicle.cp.courseNumHeadlandLanes - 1) * vehicle.cp.courseWorkWidth);
-- end;
-- end;
--- Calculate reverseOffset in case we need to reverse
local offset = turnInfo.zOffset;
if turnInfo.frontMarker > 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);
else
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 turnInfo.isHeadlandCorner then
----------------------------------------------------------
-- SWITCH TO THE NEXT LANE
----------------------------------------------------------
courseplay:debug(string.format("%s:(Turn) Direction difference is %.1f, this is a lane switch.", nameNum(vehicle), turnInfo.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;
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), turnInfo.directionChangeDeg, vehicle.cp.headland.reverseManeuverType), 14);
if turnInfo.isHarvester then
if vehicle.cp.headland.reverseManeuverType == courseplay.HEADLAND_REVERSE_MANEUVER_TYPE_STRAIGHT then
courseplay.generateTurnTypeHeadlandCornerReverseStraightCombine(vehicle, turnInfo)
elseif vehicle.cp.headland.reverseManeuverType == courseplay.HEADLAND_REVERSE_MANEUVER_TYPE_CURVE then
courseplay.generateTurnTypeHeadlandCornerReverseWithCurve(vehicle, turnInfo)
end
else
courseplay.generateTurnTypeHeadlandCornerReverseStraightTractor(vehicle, turnInfo)
end
end
cpPrintLine(14, 1);
courseplay:debug(string.format("%s:(Turn) Generated %d Turn Waypoints", nameNum(vehicle), #vehicle.cp.turnTargets), 14);
cpPrintLine(14, 3);
-- Rotate tools if needed.
if vehicle.cp.toolOffsetX ~= 0 and turnInfo.isHeadlandCorner == false then
if vehicle.cp.toolOffsetX < 0 then
AIVehicle.aiRotateLeft(vehicle);
else
AIVehicle.aiRotateRight(vehicle);
end;
end;
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 newTarget then
if newTarget.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, stage %d", nameNum(vehicle), vehicle.cp.turnStage ), 14);
return;
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 );
drawDebugLine(x1, y + 5, z1, 1, 1, 0, x2, y + 5, z2, 1, 1, 0);
local x1, _, z1 = localToWorld( realDirectionNode, -1, 0, backMarker )
local x2, _, z2 = localToWorld( realDirectionNode, 1, 0, backMarker )
drawDebugLine(x1, y + 5, z1, 1, 0, 0, x2, y + 5, z2, 1, 0, 0);
end
local dist = courseplay:distance(newTarget.posX, newTarget.posZ, vehicleX, vehicleZ);
local distOrig = dist
-- Set reversing settings.
if newTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
if reversingWorkTool and reversingWorkTool.cp.realTurningNode then
local workToolX, _, workToolZ = getWorldTranslation(reversingWorkTool.cp.realTurningNode);
local directionNodeToTurnNodeLengthOffset = courseplay:distance(workToolX, workToolZ, vehicleX, vehicleZ);
-- set the correct distance when reversing
dist = dist - (directionNodeToTurnNodeLength + (directionNodeToTurnNodeLength - directionNodeToTurnNodeLengthOffset));
if courseplay.debugChannels[14] then
local posY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, workToolX, 300, workToolZ);
drawDebugLine(vehicleX, posY + 5, vehicleZ, 1, 1, 0, workToolX, posY + 5, workToolZ, 1, 1, 0);
end
end;
-- If next wp is more than 10 meters ahead, use fieldwork speed.
elseif dist > 10 and not newTarget.turnReverse then
refSpeed = vehicle.cp.speeds.field;
end;
-- Change turn waypoint
if dist < wpChangeDistance then
courseplay:debug( string.format( "%s:(Turn) @( %.1f, %.1f) ix = %d, distOrig = %.1f, dist = %.1f, wpChangeDistance = %.1f",
nameNum( vehicle ), vehicleX, vehicleZ, vehicle.cp.curTurnIndex, distOrig, dist, wpChangeDistance ), 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 )
courseplay:lowerImplements(vehicle, false, false )
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 )
courseplay:lowerImplements( vehicle, true, true )
end
local nextCurTurnIndex = min(vehicle.cp.curTurnIndex + 1, #vehicle.cp.turnTargets);
local changeDir = ((newTarget.turnReverse and not vehicle.cp.turnTargets[nextCurTurnIndex].turnReverse) or (not newTarget.turnReverse and vehicle.cp.turnTargets[nextCurTurnIndex].turnReverse))
-- We are still moving and want to swicth directions STOP if using MR mod. And we haven't yet stoped
if math.abs(vehicle.lastSpeedReal) > 0.0001 and vehicle.mrIsMrVehicle and changeDir and not vehicle.cp.mrHasStopped then
allowedToDrive = false
-- We have finally stoped 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 newTarget.changeWhenPosible then
-- Get the world rotation of the next lane
local dx, dz = courseplay.generation:getPointDirection(vehicle.Waypoints[vehicle.cp.waypointIndex+1], vehicle.Waypoints[vehicle.cp.waypointIndex+2]);
local laneRot = Utils.getYRotationFromDirection(dx, 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 = Utils.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 oposite 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 = newTarget.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
-- on alignment course to the waypoint, ignore front marker, we want to get the vehicle itself to get to the waypoint
-- Why are we evening do this? lowerImplements doesn't occur till later in this elseif statement and we are returning out of the function before we even get there
_, _, deltaZ = worldToLocal(realDirectionNode,vehicle.Waypoints[vehicle.cp.waypointIndex].cx, vehicleY, vehicle.Waypoints[vehicle.cp.waypointIndex].cz)
lowerImplements = deltaZ < 3
courseplay:endAlignmentCourse( vehicle )
courseplay:setWaypointIndex(vehicle, vehicle.cp.waypointIndex );
return
else
_, _, deltaZ = worldToLocal(realDirectionNode,vehicle.Waypoints[vehicle.cp.waypointIndex+1].cx, vehicleY, vehicle.Waypoints[vehicle.cp.waypointIndex+1].cz)
lowerImplements = deltaZ < (isHarvester and frontMarker + 0.5 or frontMarker);
end
if newTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
lowerImplements = deltaZ > frontMarker;
end;
-- Lower implement and continue on next lane
if lowerImplements then
if vehicle.cp.abortWork == nil then
courseplay:lowerImplements(vehicle, true, true);
end;
vehicle.cp.isTurning = nil;
vehicle.cp.waitForTurnTime = vehicle.timer + turnOutTimer;
-- move on to the turnEnd (targetNode)
courseplay:setWaypointIndex(vehicle, vehicle.cp.waypointIndex + 1);
-- and then to the next wp in front of us.
courseplay:setWaypointIndex(vehicle, courseplay:getNextFwdPoint(vehicle, true));
vehicle.cp.ppc:initialize()
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 newTarget.turnEnd and vehicle.cp.curTurnIndex == #vehicle.cp.turnTargets then
vehicle.cp.turnStage = 3;
return;
end;
local dist = courseplay:distance(newTarget.posX, newTarget.posZ, vehicleX, vehicleZ);
-- Set reverseing settings.
if newTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
if reversingWorkTool and reversingWorkTool.cp.realTurningNode then
local workToolX, _, workToolZ = getWorldTranslation(reversingWorkTool.cp.realTurningNode);
local directionNodeToTurnNodeLengthOffset = courseplay:distance(workToolX, workToolZ, vehicleX, vehicleZ);
-- set the correct distance when reversing
dist = dist - (directionNodeToTurnNodeLength + (directionNodeToTurnNodeLength - directionNodeToTurnNodeLengthOffset));
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,vehicle.Waypoints[vehicle.cp.waypointIndex+1].cx, vehicleY, vehicle.Waypoints[vehicle.cp.waypointIndex+1].cz)
local lowerImplements = deltaZ < (isHarvester and frontMarker + 0.5 or frontMarker);
if newTarget.turnReverse then
refSpeed = vehicle.cp.speeds.reverse;
lowerImplements = deltaZ > frontMarker;
end;
-- Lower implement and continue on next lane
if lowerImplements then
if vehicle.cp.abortWork == nil then
courseplay:lowerImplements(vehicle, true, true);
end;
vehicle.cp.isTurning = nil;
vehicle.cp.waitForTurnTime = vehicle.timer + turnOutTimer;
courseplay:setWaypointIndex(vehicle, vehicle.cp.waypointIndex + 1);
courseplay:setWaypointIndex(vehicle, courseplay:getNextFwdPoint(vehicle, true));
vehicle.cp.ppc:initialize()
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 raice implement and togo turn stage 1
----------------------------------------------------------
else
--- Add WP to follow while doing last bit before raising Implement
if not newTarget then
local extraForward = 0;
if backMarker < 0 then
extraForward = abs(backMarker);
end;
local dx, dz = courseplay.generation:getPointDirection(vehicle.Waypoints[vehicle.cp.waypointIndex-1], vehicle.Waypoints[vehicle.cp.waypointIndex]);
local cx, cz = courseplay:getVehicleOffsettedCoords(vehicle, vehicle.Waypoints[vehicle.cp.waypointIndex].cx, vehicle.Waypoints[vehicle.cp.waypointIndex].cz);
local posX, posZ = cx + (extraForward + 10) * dx, cz + (extraForward + 10) * dz;
courseplay:addTurnTarget(vehicle, posX, posZ);
end;
if vehicle.cp.lowerToolThisTurnLoop then
if vehicle.getIsTurnedOn ~= nil and not vehicle:getIsTurnedOn() then
vehicle:setIsTurnedOn(true, false);
end;
courseplay:lowerImplements(vehicle, true, true);
vehicle.cp.lowerToolThisTurnLoop = false;
end;
if vehicle.isStrawEnabled then
vehicle.cp.savedNoStopOnTurn = vehicle.cp.noStopOnTurn
vehicle.cp.noStopOnTurn = false;
turnTimer = vehicle.strawToggleTime or 5;
elseif vehicle.cp.savedNoStopOnTurn ~= nil then
vehicle.cp.noStopOnTurn = vehicle.cp.savedNoStopOnTurn;
vehicle.cp.savedNoStopOnTurn = nil;
end;
--- Use the speed limit if we are still working and turn speed is higher that the speed limit.
refSpeed = courseplay:getSpeedWithLimiter(vehicle, refSpeed);
local wpX, wpZ = vehicle.Waypoints[vehicle.cp.waypointIndex].cx, vehicle.Waypoints[vehicle.cp.waypointIndex].cz;
local _, _, disZ = worldToLocal(realDirectionNode, wpX, getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, wpX, 300, wpZ), wpZ);
-- we don't want to turn off anything during a headland turn.
local _, isHeadlandCorner = getDirectionChangeOfTurn( vehicle )
if disZ < backMarker then
if not vehicle.cp.noStopOnTurn then
vehicle.cp.waitForTurnTime = vehicle.timer + turnTimer;
end;
-- raise implements only if this is not a headland turn; in headland
-- turns the turn waypoint attributs will control when to raise/lower implements
if not isHeadlandCorner then
courseplay:lowerImplements(vehicle, false, false);
end
vehicle.cp.turnStage = 1;
end;
end;
----------------------------------------------------------
--Set the driving direction
----------------------------------------------------------
if newTarget then
local posX, posZ = newTarget.revPosX or newTarget.posX, newTarget.revPosZ or newTarget.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 newTarget.turnReverse then
lx, lz, moveForwards = courseplay:goReverse(vehicle,lx,lz);
end;
end;
----------------------------------------------------------
-- Debug prints: Show Current Waypoint
----------------------------------------------------------
if courseplay.debugChannels[12] and newTarget then
local posX, posZ = newTarget.revPosX or newTarget.posX, newTarget.revPosZ or newTarget.posZ;
local posY = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, posX, 300, posZ);
drawDebugLine(posX, posY + 3, posZ, 0, 0, 1, posX, posY + 4, posZ, 0, 0, 1); -- Blue Line
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
--vehicle,dt,steeringAngleLimit,acceleration,slowAcceleration,slowAngleLimit,allowedToDrive,moveForwards,lx,lz,maxSpeed,slowDownFactor,angle
if newTarget and ((newTarget.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;
AIVehicleUtil.driveToPoint(vehicle, dt, directionForce, allowedToDrive, moveForwards, dtpX, dtpZ, refSpeed);
end;
courseplay:setTrafficCollision(vehicle, lx, lz, true);
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:generateTurnStraitPoints(vehicle, fromPoint, toPoint, true, nil, turnInfo.reverseWPChangeDistance);
end;
--- Get the 2 circle center cordinate
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:generateTurnStraitPoints(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:generateTurnStraitPoints(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:generateTurnStraitPoints(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:generateTurnStraitPoints(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:generateTurnStraitPoints(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 = localToWorld(turnInfo.directionNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnRadius);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.directionNode, (vehicle.cp.courseWorkWidth - turnInfo.turnRadius - turnInfo.turnDiameter) * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnRadius);
courseplay:generateTurnStraitPoints(vehicle, fromPoint, toPoint);
--- Generate the second turn circles
center.x,_,center.z = localToWorld(turnInfo.directionNode, (vehicle.cp.courseWorkWidth - turnInfo.turnRadius - turnInfo.turnDiameter) * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnDiameter);
startDir.x,_,startDir.z = localToWorld(turnInfo.directionNode, (vehicle.cp.courseWorkWidth - turnInfo.turnRadius - turnInfo.turnDiameter) * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnRadius);
stopDir.x,_,stopDir.z = localToWorld(turnInfo.directionNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter) * turnInfo.direction, 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 = localToWorld(turnInfo.directionNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter) * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset + turnInfo.turnDiameter);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, turnInfo.turnDiameter * turnInfo.direction, 0, turnInfo.reverseOffset);
courseplay:generateTurnStraitPoints(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 of 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 = localToWorld(turnInfo.directionNode, turnInfo.turnDiameter * turnInfo.direction, 0, turnInfo.zOffset - turnInfo.reverseOffset);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter) * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnDiameter);
courseplay:generateTurnStraitPoints(vehicle, fromPoint, toPoint);
--- Generate the second turn circles
center.x,_,center.z = localToWorld(turnInfo.targetNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter - turnInfo.turnRadius) * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnDiameter);
startDir.x,_,startDir.z = localToWorld(turnInfo.targetNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter) * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnDiameter);
stopDir.x,_,stopDir.z = localToWorld(turnInfo.targetNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter - turnInfo.turnRadius) * turnInfo.direction, 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 = localToWorld(turnInfo.targetNode, (vehicle.cp.courseWorkWidth - turnInfo.turnDiameter - turnInfo.turnRadius) * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnRadius);
toPoint.x, _, toPoint.z = localToWorld(turnInfo.targetNode, turnInfo.turnRadius * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnRadius);
courseplay:generateTurnStraitPoints(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.turnRadius * turnInfo.direction, 0, turnInfo.reverseOffset - turnInfo.turnRadius);
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);
courseplay:generateTurnStraitPoints(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:generateTurnStraitPoints(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:generateTurnStraitPoints(vehicle, stopDir, toPoint, nil, true);
end;
end;
function courseplay:generateTurnTypeOhmTurn(vehicle, turnInfo)
cpPrintLine(14, 3);
courseplay:debug(string.format("%s:(Turn) Using Ohm Turn", nameNum(vehicle)), 14);
cpPrintLine(14, 3);
local posX, posZ;
--- 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);
--- Target is behind of us
local targetOffsetZ = 0;
if turnInfo.targetDeltaZ < 0 then
targetOffsetZ = abs(turnInfo.targetDeltaZ);
end;
if turnInfo.frontMarker > 0 then
targetOffsetZ = targetOffsetZ + (turnInfo.frontMarker * 1.5);
end;