forked from Courseplay/Courseplay_FS25
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse.lua
More file actions
1879 lines (1702 loc) · 74.5 KB
/
Course.lua
File metadata and controls
1879 lines (1702 loc) · 74.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
This file is part of Courseplay (https://github.com/Courseplay/Courseplay_FS25)
Copyright (C) 2018-2022 Peter Va9ko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
---@class Course
Course = CpObject()
--- Course constructor
---@param waypoints Waypoint[] table of waypoints of the course
---@param temporary boolean|nil optional, default false is this a temporary course?
---@param first number|nil optional, index of first waypoint to use
---@param last number|nil optional, index of last waypoint to use to construct of the course
function Course:init(vehicle, waypoints, temporary, first, last)
-- add waypoints from current vehicle course
---@type Waypoint[]
self.waypoints = Course.initWaypoints()
for i = first or 1, last or #waypoints do
table.insert(self.waypoints, Waypoint(waypoints[i]))
end
-- offset to apply to every position
self.offsetX, self.offsetZ = 0, 0
self.temporaryOffsetX, self.temporaryOffsetZ = CpSlowChangingObject(0, 0), CpSlowChangingObject(0, 0)
self.numberOfHeadlands = 0
self.workWidth = 0
self.name = ''
self.editedByCourseEditor = false
self.nVehicles = 1
-- only for logging purposes
self.vehicle = vehicle
self.temporary = temporary or false
self.currentWaypoint = 1
self.length = 0
self.totalTurns = 0
self:enrichWaypointData()
end
function Course:getDebugTable()
return {
{ name = "numWp", value = self:getNumberOfWaypoints() },
{ name = "workWidth", value = self.workWidth },
{ name = "curWpIx", value = self:getCurrentWaypointIx() },
{ name = "length", value = self.length },
{ name = "numTurns", value = self.totalTurns },
{ name = "offsetX", value = self.offsetX },
{ name = "offsetZ", value = self.offsetZ },
{ name = "nVehicles", value = self.nVehicles },
{ name = "numHeadlands", value = self.numberOfHeadlands },
{ name = "totalTurns", value = self.totalTurns },
}
end
function Course:setName(name)
self.name = name
end
function Course:setVehicle(vehicle)
self.vehicle = vehicle
end
function Course:getVehicle()
return self.vehicle
end
function Course:getName()
return self.name
end
function Course:setEditedByCourseEditor()
self.editedByCourseEditor = true
end
function Course:wasEditedByCourseEditor()
return self.editedByCourseEditor
end
function Course:getAllWaypoints()
return self.waypoints
end
--- Function to create the waypoints table in the Course object. This makes sure, that
--- the index is always within the bounds of the table, and avoids crashes, but may result
--- in other errors.
---@return table
function Course.initWaypoints()
return setmetatable({}, {
-- add a function to clamp the index between 1 and #self.waypoints
__index = function(tbl, key)
local result = rawget(tbl, key)
if not result and type(key) == "number" then
result = rawget(tbl, math.min(math.max(1, key), #tbl))
end
return result
end
})
end
--- Current offset to apply. getWaypointPosition() will always return the position adjusted by the
-- offset. The x and z offset are in the waypoint's coordinate system, waypoints are directed towards
-- the next waypoint, so a z = 1 offset will move the waypoint 1m forward, x = 1 1 m to the right (when
-- looking in the drive direction)
--- IMPORTANT: the offset for multitool (laneOffset) must not be part of this as it is already part of the
--- course,
--- @see Course#calculateOffsetCourse
function Course:setOffset(x, z)
self.offsetX, self.offsetZ = x, z
end
function Course:getOffset()
return self.offsetX, self.offsetZ
end
--- Temporary offset to apply. This is to use an offset temporarily without overwriting the normal offset of the course
function Course:setTemporaryOffset(x, z, t)
self.temporaryOffsetX:set(x, t)
self.temporaryOffsetZ:set(z, t)
end
function Course:changeTemporaryOffsetX(dx, t)
self.temporaryOffsetX:set(self.temporaryOffsetX:get() + dx, t)
end
function Course:setWorkWidth(w)
self.workWidth = w
end
function Course:getWorkWidth()
return self.workWidth
end
function Course:getNumberOfHeadlands()
return self.numberOfHeadlands
end
--- get number of waypoints in course
function Course:getNumberOfWaypoints()
return #self.waypoints
end
---@return Waypoint
function Course:getWaypoint(ix)
return self.waypoints[ix]
end
function Course:getMultiTools()
return self.nVehicles or 1
end
--- Is this a temporary course? Can be used to differentiate between recorded and dynamically generated courses
-- The Course() object does not use this attribute for anything
function Course:isTemporary()
return self.temporary
end
-- add missing angles and world directions from one waypoint to the other
-- PPC relies on waypoint angles, the world direction is needed to calculate offsets
function Course:enrichWaypointData(startIx)
if #self.waypoints < 2 then
return
end
if not startIx then
-- initialize only if recalculating the whole course, otherwise keep (and update) the old values)
self.length = 0
end
for i = startIx or 1, #self.waypoints - 1 do
self.waypoints[i].dToHere = self.length
local cx, _, cz = self.waypoints[i]:getPosition()
local nx, _, nz = self.waypoints[i + 1]:getPosition()
local dToNext = MathUtil.getPointPointDistance(cx, cz, nx, nz)
self.waypoints[i].dToNext = dToNext
self.length = self.length + dToNext
if self:isTurnStartAtIx(i) then
self.totalTurns = self.totalTurns + 1
end
if self:isTurnEndAtIx(i) then
self.dFromLastTurn = 0
elseif self.dFromLastTurn then
self.dFromLastTurn = self.dFromLastTurn + dToNext
end
self.waypoints[i].turnsToHere = self.totalTurns
-- TODO: looks like we may end up with the first two waypoint of a course being the same. This takes care
-- of setting dx/dz to 0 (instead of NaN) but should investigate as it does not make sense
if MathUtil.vector2Length(nx - cx, nz - cz) > 0 then
local dx, dz = MathUtil.vector2Normalize(nx - cx, nz - cz)
self.waypoints[i].dx, self.waypoints[i].dz = dx, dz
self.waypoints[i].yRot = MathUtil.getYRotationFromDirection(dx, dz)
else
self.waypoints[i].dx, self.waypoints[i].dz = 0, 0
-- NaN or both 0, use the direction of the previous waypoint
self.waypoints[i].yRot = self.waypoints[i - 1].yRot or 0
end
self.waypoints[i].angle = math.deg(self.waypoints[i].yRot)
self.waypoints[i].calculatedRadius = i == 1 and math.huge or self:calculateRadius(i)
self.waypoints[i].curvature = i == 1 and 0 or 1 / self:calculateSignedRadius(i)
if (self:isReverseAt(i) and not self:switchingToForwardAt(i)) or self:switchingToReverseAt(i) then
-- X offset must be reversed at waypoints where we are driving in reverse
self.waypoints[i]:setReverseOffset(true)
end
end
-- make the last waypoint point to the same direction as the previous so we don't
-- turn towards the first when ending the course. (the course generator points the last
-- one to the first, should probably be changed there)
self.waypoints[#self.waypoints].angle = self.waypoints[#self.waypoints - 1].angle
self.waypoints[#self.waypoints].yRot = self.waypoints[#self.waypoints - 1].yRot
self.waypoints[#self.waypoints].dx = self.waypoints[#self.waypoints - 1].dx
self.waypoints[#self.waypoints].dz = self.waypoints[#self.waypoints - 1].dz
self.waypoints[#self.waypoints].dToNext = 0
self.waypoints[#self.waypoints].dToHere = self.length
self.waypoints[#self.waypoints].turnsToHere = self.totalTurns
self.waypoints[#self.waypoints].calculatedRadius = math.huge
self.waypoints[#self.waypoints].curvature = 0
self.waypoints[#self.waypoints]:setReverseOffset(self:isReverseAt(#self.waypoints))
-- now add some metadata for the combines
local dToNextTurn, lNextRow, nextRowStartIx = 0, 0, 0
local dToNextDirectionChange, nextDirectionChangeIx = 0, 0
local turnFound = false
local directionChangeFound = false
for i = #self.waypoints - 1, 1, -1 do
if turnFound then
dToNextTurn = dToNextTurn + self.waypoints[i].dToNext
self.waypoints[i].dToNextTurn = dToNextTurn
self.waypoints[i].lNextRow = lNextRow
self.waypoints[i].nextRowStartIx = nextRowStartIx
end
if self:isTurnStartAtIx(i) then
lNextRow = dToNextTurn
nextRowStartIx = i + 1
dToNextTurn = 0
turnFound = true
end
if directionChangeFound then
dToNextDirectionChange = dToNextDirectionChange + self.waypoints[i].dToNext
self.waypoints[i].dToNextDirectionChange = dToNextDirectionChange
self.waypoints[i].nextDirectionChangeIx = nextDirectionChangeIx
end
if self:switchingDirectionAt(i) then
dToNextDirectionChange = 0
nextDirectionChangeIx = i
directionChangeFound = true
end
end
CpUtil.debugVehicle(CpDebug.DBG_COURSES, self.vehicle or CpUtil.getCurrentVehicle(),
'Course with %d waypoints created/updated, %.1f meters, %d turns', #self.waypoints, self.length, self.totalTurns)
end
function Course:getDeltaAngle(ix)
return CpMathUtil.getDeltaAngle(self.waypoints[ix].yRot, self.waypoints[ix - 1].yRot)
end
function Course:calculateSignedRadius(ix)
return CpMathUtil.divide(self:getDistanceToNextWaypoint(ix), (2 * math.sin(self:getDeltaAngle(ix) / 2)))
end
function Course:calculateRadius(ix)
return math.abs(self:calculateSignedRadius(ix))
end
--- Is this the same course as otherCourse?
-- TODO: is there a hash we could use instead?
function Course:equals(other)
if #self.waypoints ~= #other.waypoints then
return false
end
-- for now just check the coordinates of the first waypoint
if self.waypoints[1].x - other.waypoints[1].x > 0.01 then
return false
end
if self.waypoints[1].z - other.waypoints[1].z > 0.01 then
return false
end
-- same number of waypoints, first waypoint same coordinates, equals!
return true
end
--- A super simple hash to identify and compare courses (see convoy)
function Course:getHash()
local hash = ''
for i = 1, math.min(20, #self.waypoints) do
hash = hash .. string.format('%d%d', self.waypoints[i].x, self.waypoints[i].z)
end
return hash
end
function Course:setCurrentWaypointIx(ix)
self.currentWaypoint = ix
end
function Course:getCurrentWaypointIx()
return self.currentWaypoint
end
function Course:setLastPassedWaypointIx(ix)
self.lastPassedWaypoint = ix
end
function Course:getLastPassedWaypointIx()
return self.lastPassedWaypoint
end
function Course:isReverseAt(ix)
return self.waypoints[math.min(math.max(1, ix), #self.waypoints)].rev
end
function Course:getLastReverseAt(ix)
for i = ix, #self.waypoints do
if not self.waypoints[i].rev then
return i - 1
end
end
end
function Course:isForwardOnly()
for _, wp in ipairs(self.waypoints) do
if wp.rev then
return false
end
end
return true
end
function Course:isTurnStartAtIx(ix)
-- Don't start turns at the last waypoint
-- TODO: do a row finish maneuver instead
return ix < #self.waypoints and
-- don't start any turns just before a connecting path as there the pathfinder should take over
(self.waypoints[ix]:isRowEnd() and
not self:isOnConnectingPath(ix + 1) and
not self:shouldUsePathfinderToNextWaypoint(ix)) or
(self.waypoints[ix + 1] and self.waypoints[ix + 1]:isHeadlandTurn() and
self.waypoints[ix + 2] and not self:isOnConnectingPath(ix + 2))
end
function Course:isHeadlandTurnAtIx(ix)
return ix <= #self.waypoints and self.waypoints[ix]:isHeadlandTurn()
end
function Course:isTurnEndAtIx(ix)
return (self.waypoints[ix]:isRowStart() and not self:shouldUsePathfinderToThisWaypoint(ix)) or
self.waypoints[ix]:isHeadlandTurn()
end
function Course:shouldUsePathfinderToNextWaypoint(ix)
return self.waypoints[ix]:shouldUsePathfinderToNextWaypoint() or
(ix < #self.waypoints and self.waypoints[ix + 1]:shouldUsePathfinderToThisWaypoint())
end
function Course:shouldUsePathfinderToThisWaypoint(ix)
return self.waypoints[ix]:shouldUsePathfinderToThisWaypoint() or
(ix > 1 and self.waypoints[ix - 1]:shouldUsePathfinderToNextWaypoint())
end
function Course:skipOverTurnStart(ix)
if self:isTurnStartAtIx(ix) then
return ix + 1
else
return ix
end
end
--- Is this waypoint on a connecting track, that is, a transfer path between
-- a headland and the up/down rows where there's no fieldwork to do.
function Course:isOnConnectingPath(ix)
return ix <= #self.waypoints and self.waypoints[ix]:isOnConnectingPath()
end
function Course:switchingDirectionAt(ix)
return self:switchingToForwardAt(ix) or self:switchingToReverseAt(ix)
end
function Course:getNextDirectionChangeFromIx(ix)
for i = ix, #self.waypoints do
if self:switchingDirectionAt(i) then
return i
end
end
end
function Course:switchingToReverseAt(ix)
return not self:isReverseAt(ix) and self:isReverseAt(ix + 1)
end
function Course:switchingToForwardAt(ix)
return self:isReverseAt(ix) and not self:isReverseAt(ix + 1)
end
function Course:getHeadlandNumber(ix)
return self.waypoints[ix].attributes:getHeadlandPassNumber()
end
---@param ix number
---@param n number|nil headland pass number
---@param boundaryId string|nil boundary id of the headland
function Course:isOnHeadland(ix, n, boundaryId)
ix = ix or self.currentWaypoint
if n then
if boundaryId == nil then
return self.waypoints[ix].attributes:getHeadlandPassNumber() == n
else
return self.waypoints[ix].attributes:getHeadlandPassNumber() == n and
self.waypoints[ix]:getBoundaryId() == boundaryId
end
else
return self.waypoints[ix].attributes:getHeadlandPassNumber() ~= nil
end
end
---@param ix number
---@return boolean|nil true if ix is on a clockwise headland (around the field, or around an island). False if
--- it is on a counterclockwise headland, and nil, if is is not on a headland.
function Course:isOnClockwiseHeadland(ix)
local boundaryId = self.waypoints[ix].attributes:getBoundaryId()
if boundaryId == nil then
return nil
end
if CourseGenerator.isHeadland(boundaryId) then
return self.headlandClockwise
elseif CourseGenerator.isIslandHeadland(boundaryId) then
return self.islandHeadlandClockwise
end
return nil
end
function Course:isHeadlandTransition(ix)
return self.waypoints[ix]:isHeadlandTransition()
end
function Course:isOnOutermostHeadland(ix)
return self.waypoints[ix].attributes:getHeadlandPassNumber() == 1
end
function Course:startsWithHeadland()
return self:isOnHeadland(1)
end
---@param n number number of headland to get, 1 -> number of headlands, 1 is the outermost
---@param boundaryId string|nil id of the boundary to return only the points that are on the same field boundary
--- or island headland
---@return Polygon headland as a polygon (x, y)
function Course:getHeadland(n, boundaryId)
local headland = Polygon()
local first, last, step
if self:startsWithHeadland() then
first, last, step = 1, self:getNumberOfWaypoints(), 1
else
-- if the course ends with the headland, start at the end to avoid headlands around the
-- islands in the center of the field
first, last, step = self:getNumberOfWaypoints(), 1, -1
end
for i = first, last, step do
-- do not want to include the transition and the connecting path parts as those are overlap with the first part
-- of the headland confusing the shortest path finding
if self:isOnHeadland(i, n, boundaryId) and not self:isHeadlandTransition(i) and not self:isOnConnectingPath(i) then
local x, _, z = self:getWaypointPosition(i)
headland:append({ x = x, y = -z })
end
if #headland > 0 and not self:isOnHeadland(i, n) then
-- stop after we leave the headland around the field boundary or when we already found our headland
-- and now on a different one
-- as we don't want to include headlands around islands.
break
end
end
return headland
end
function Course:getTurnControls(ix)
return self.waypoints[ix].turnControls
end
function Course:setUseTightTurnOffset(ix)
return self.waypoints[ix]:setUseTightTurnOffset()
end
function Course:getUseTightTurnOffset(ix)
return self.waypoints[ix]:getUseTightTurnOffset()
end
--- Returns the position of the waypoint at ix with the current offset applied.
---@param ix number waypoint index
---@return number, number, number x, y, z
function Course:getWaypointPosition(ix)
if self:isTurnStartAtIx(ix) and not self:isHeadlandTurnAtIx(ix) then
-- turn start waypoints point to the turn end wp, for example at the row end they point 90 degrees to the side
-- from the row direction. This is a problem when there's an offset so use the direction of the previous wp
-- when calculating the offset for a turn start wp, except for headlands turns where we actually drive the
-- section between turn start and turn end.
return self:getOffsetPositionWithOtherWaypointDirection(ix, ix - 1)
else
return self.waypoints[ix]:getOffsetPosition(self.offsetX + self.temporaryOffsetX:get(), self.offsetZ + self.temporaryOffsetZ:get())
end
end
---Return the offset coordinates of waypoint ix as if it was pointing to the same direction as waypoint ixDir
function Course:getOffsetPositionWithOtherWaypointDirection(ix, ixDir)
return self.waypoints[ix]:getOffsetPosition(self.offsetX + self.temporaryOffsetX:get(), self.offsetZ + self.temporaryOffsetZ:get(),
self.waypoints[ixDir].dx, self.waypoints[ixDir].dz)
end
-- distance between (px,pz) and the ix waypoint
function Course:getDistanceBetweenPointAndWaypoint(px, pz, ix)
return self.waypoints[ix]:getDistanceFromPoint(px, pz)
end
function Course:getDistanceBetweenVehicleAndWaypoint(vehicle, ix)
return self.waypoints[ix]:getDistanceFromVehicle(vehicle)
end
--- get waypoint position in the node's local coordinates
function Course:getWaypointLocalPosition(node, ix)
local x, y, z = self:getWaypointPosition(ix)
local dx, dy, dz = worldToLocal(node, x, y, z)
return dx, dy, dz
end
function Course:getWaypointAngleDeg(ix)
return self.waypoints[math.min(#self.waypoints, ix)].angle
end
--- Gets the world directions of the waypoint.
---@param ix number
---@return number x world direction
---@return number z world direction
function Course:getWaypointWorldDirections(ix)
local wp = self.waypoints[math.min(#self.waypoints, ix)]
return wp.dx, wp.dz
end
--- Get the driving direction at the waypoint. y rotation points in the direction
--- of the next waypoint, but at the last wp before a direction change this is the opposite of the driving
--- direction, since we want to reach that last waypoint
function Course:getYRotationCorrectedForDirectionChanges(ix)
if ix == #self.waypoints or self:switchingDirectionAt(ix) and ix > 1 then
-- last waypoint before changing direction, use the yRot from the previous waypoint
return self.waypoints[ix - 1].yRot
else
return self.waypoints[ix].yRot
end
end
-- This is the radius calculated when the course is created.
function Course:getCalculatedRadiusAtIx(ix)
local r = self.waypoints[ix].calculatedRadius
if r ~= r then
-- radius can be nan
return nil
else
return r
end
end
--- Get the minimum radius within d distance from waypoint ix
---@param ix number waypoint index to start
---@param d number distance in meters to look forward
---@return number the minimum radius within d distance from waypoint ix
function Course:getMinRadiusWithinDistance(ix, d)
local ixAtD = self:getNextWaypointIxWithinDistance(ix, d) or ix
local minR, count = math.huge, 0
for i = ix, ixAtD do
if self:isTurnStartAtIx(i) or self:isTurnEndAtIx(i) then
-- the turn maneuver code will take care of speed
return nil
end
local r = self:getCalculatedRadiusAtIx(i)
if r and r < minR then
count = count + 1
minR = r
end
end
return count > 0 and minR or nil
end
--- Get the Y rotation of a waypoint (pointing into the direction of the next)
function Course:getWaypointYRotation(ix)
local i = ix
-- at the last waypoint use the incoming direction
if ix >= #self.waypoints then
i = #self.waypoints - 1
elseif ix < 1 then
i = 1
end
local cx, _, cz = self:getWaypointPosition(i)
local nx, _, nz = self:getWaypointPosition(i + 1)
-- if current and next are at the same position, to avoid division by zero
if MathUtil.vector2Length(nx - cx, nz - cz) < 0.00001 then
-- use the direction of the previous waypoint if exists, otherwise the next. This is to make sure that
-- the WaypointNode used by the PPC has a valid direction
if i > 1 then
return self.waypoints[i - 1].yRot
else
return self.waypoints[i + 1].yRot
end
return 0
end
local dx, dz = MathUtil.vector2Normalize(nx - cx, nz - cz)
return MathUtil.getYRotationFromDirection(dx, dz)
end
---@return number RidgeMarkerController.RIDGE_MARKER_NONE, RidgeMarkerController.RIDGE_MARKER_LEFT, RidgeMarkerController.RIDGE_MARKER_RIGHT
function Course:getRidgeMarkerState(ix)
-- set ridge marker only if we are absolutely sure that a side is not worked
if self.waypoints[ix].attributes:isLeftSideNotWorked() then
return RidgeMarkerController.RIDGE_MARKER_LEFT
elseif self.waypoints[ix].attributes:isRightSideNotWorked() then
return RidgeMarkerController.RIDGE_MARKER_RIGHT
else
return RidgeMarkerController.RIDGE_MARKER_NONE
end
end
function Course:isLeftSideWorked(ix)
return self.waypoints[ix].attributes:isLeftSideWorked()
end
---@return boolean true if the next 180 turn is to the left, false if to the right, nil if we don't know
function Course:isNextTurnLeft(ix)
if self.waypoints[ix].nextRowStartIx == nil then
return nil
else
local turnStartWaypointIx = self.waypoints[ix].nextRowStartIx - 1
return CpMathUtil.getDeltaAngle(self.waypoints[turnStartWaypointIx].yRot, self.waypoints[turnStartWaypointIx - 1].yRot) < 0
end
end
--- Should the plow be rotated to the left at the waypoint ix?
--- On the headland just check which side was worked last, on the center, check the direction of the next turn
--- as at the first pass both sides are unworked and need some other indication on which side the plow should be
function Course:shouldPlowBeOnTheLeft(ix)
local plowShouldBeOnTheLeft
if self:isOnHeadland(ix) then
local clockwise = self:isOnClockwiseHeadland(ix)
plowShouldBeOnTheLeft = not clockwise
CpUtil.debugVehicle(CpDebug.DBG_TURN, self.vehicle, 'On a headland (clockwise %s), plow should be on the left %s', tostring(clockwise), tostring(plowShouldBeOnTheLeft))
else
local isNextTurnLeft = self:isNextTurnLeft(ix)
if isNextTurnLeft == nil then
-- don't know if left or right, so just use the last worked side
plowShouldBeOnTheLeft = self:isLeftSideWorked(ix)
CpUtil.debugVehicle(CpDebug.DBG_TURN, self.vehicle, 'On the center, next turn direction unknown, plow should be on the left %s', tostring(plowShouldBeOnTheLeft))
else
plowShouldBeOnTheLeft = not isNextTurnLeft
CpUtil.debugVehicle(CpDebug.DBG_TURN, self.vehicle, 'On the center, plow should be on the left %s', tostring(plowShouldBeOnTheLeft))
end
end
return plowShouldBeOnTheLeft
end
function Course:getIxRollover(ix)
if ix > #self.waypoints then
return ix - #self.waypoints
elseif ix < 1 then
return #self.waypoints - ix
end
return ix
end
function Course:isLastWaypointIx(ix)
return #self.waypoints == ix
end
function Course:endsInReverse()
return self:isReverseAt(self:getNumberOfWaypoints())
end
function Course:print()
for i = 1, #self.waypoints do
local p = self.waypoints[i]
print(string.format('%d: x=%.1f z=%.1f a=%.1f yRot=%.1f re=%s rs=%s r=%s d=%.1f t=%d l=%s p=%s tt=%s dx=%.1f dz=%.1f',
i, p.x, p.z, p.angle or -1, math.deg(p.yRot or 0),
tostring(p:isRowEnd()), tostring(p:isRowStart()), tostring(p.rev), p.dToHere or -1, p.turnsToHere or -1,
tostring(p.attributes:getHeadlandPassNumber()), tostring(p.pipeInFruit), tostring(p.useTightTurnOffset), p.dx, p.dz))
end
end
function Course:getDistanceToNextWaypoint(ix)
return self.waypoints[math.min(#self.waypoints, ix)].dToNext
end
function Course:getDistanceBetweenWaypoints(a, b)
return math.abs(self.waypoints[a].dToHere - self.waypoints[b].dToHere)
end
function Course:getDistanceFromFirstWaypoint(ix)
return self.waypoints[ix].dToHere
end
function Course:getDistanceToLastWaypoint(ix)
return self.length - self.waypoints[ix].dToHere
end
--- How far are we from the waypoint marked as the beginning of the up/down rows?
---@param ix number start searching from this index. Will stop searching after 100 m
---@return number, number of meters or math.huge if no start up/down row waypoint found within 100 meters and the
--- index of the first up/down waypoint
function Course:getDistanceToFirstUpDownRowWaypoint(ix)
local d = 0
local isConnectingPath = false
for i = ix, #self.waypoints - 1 do
isConnectingPath = isConnectingPath or self.waypoints[i].attributes:isOnConnectingPath()
d = d + self.waypoints[i].dToNext
if self.waypoints[i].attributes:getHeadlandPassNumber() and not self.waypoints[i + 1].attributes:getHeadlandPassNumber() and isConnectingPath then
return d, i + 1
end
if d > 1000 then
return math.huge, nil
end
end
return math.huge, nil
end
function Course:hasWaypointWithPropertyAround(ix, forward, backward, hasProperty)
for i = math.max(ix - backward + 1, 1), math.min(ix + forward - 1, #self.waypoints) do
if hasProperty(self.waypoints[i]) then
-- one of the waypoints around ix has this property
return true, i
end
end
return false
end
--- Is there an turn (start or end) around ix?
---@param ix number waypoint index to look around
---@param distance number distance in meters to look around the waypoint
---@return boolean true if any of the waypoints are turn start/end point
function Course:hasTurnWithinDistance(ix, distance)
return self:hasWaypointWithPropertyWithinDistance(ix, distance, function(p)
return p:isRowEnd() or p:isRowStart()
end)
end
function Course:hasWaypointWithPropertyWithinDistance(ix, distance, hasProperty)
-- search backwards first
local d = 0
for i = math.max(1, ix - 1), 1, -1 do
if hasProperty(self.waypoints[i]) then
return true, i
end
d = d + self.waypoints[i].dToNext
if d > distance then
break
end
end
-- search forward
d = 0
for i = ix, #self.waypoints - 1 do
if hasProperty(self.waypoints[i]) then
return true, i
end
d = d + self.waypoints[i].dToNext
if d > distance then
break
end
end
return false
end
--- Get the index of the first waypoint from ix which is at least distance meters away
---@param backward boolean search backward if true
---@return number, number index and exact distance
function Course:getNextWaypointIxWithinDistance(ix, distance, backward)
local d = 0
local from, to, step = ix, #self.waypoints - 1, 1
if backward then
from, to, step = ix - 1, 1, -1
end
for i = from, to, step do
d = d + self.waypoints[i].dToNext
if d > distance then
return i + 1, d
end
end
-- at the end/start of course return last/first wp
return to + 1, d
end
--- Get the index of the first waypoint from ix which is at least distance meters away (search backwards)
function Course:getPreviousWaypointIxWithinDistance(ix, distance)
local d = 0
for i = math.max(1, ix - 1), 1, -1 do
d = d + self.waypoints[i].dToNext
if d > distance then
return i
end
end
return nil
end
--- Get the index of the first waypoint from ix which is at least distance meters away (search backwards)
--- or the index of the last turn end waypoint, whichever comes first
function Course:getPreviousWaypointIxWithinDistanceOrToTurnEnd(ix, distance)
local d = 0
if self:isTurnEndAtIx(ix) then
return ix
end
for i = math.max(1, ix - 1), 1, -1 do
d = d + self.waypoints[i].dToNext
if self:isTurnEndAtIx(i) or d > distance then
return i
end
end
return nil
end
function Course:getLength()
return self.length
end
--- Is there a turn between the two waypoints?
function Course:isTurnBetween(ix1, ix2)
return self.waypoints[ix1].turnsToHere ~= self.waypoints[ix2].turnsToHere
end
function Course:getRemainingDistanceAndTurnsFrom(ix)
local distance = self.length - self.waypoints[ix].dToHere
local numTurns = self.totalTurns - self.waypoints[ix].turnsToHere
return distance, numTurns
end
function Course:getNextFwdWaypointIx(ix)
for i = ix, #self.waypoints do
if not self:isReverseAt(i) then
return i
end
end
CpUtil.debugVehicle(CpDebug.DBG_COURSES, self.vehicle, 'Course: could not find next forward waypoint after %d', ix)
return ix
end
---@param ix number waypoint index to start the search at
---@param vehicleNode number node representing the vehicle position
---@param maxDx number maximum lateral deviation of the found waypoint
---@param lookAhead number number of waypoints in front of ix to search for, default 10
---@return number index of next waypoint in front of us, or ix when not found
---@return boolean true if we found the next waypoint
function Course:getNextFwdWaypointIxFromVehiclePosition(ix, vehicleNode, maxDx, lookAhead)
-- only look at the next few waypoints, we don't want to find anything far away, really, it should be in front of us
for i = ix, math.min(ix + (lookAhead or 10), #self.waypoints) do
if not self:isReverseAt(i) then
local uX, uY, uZ = self:getWaypointPosition(i)
local dx, _, dz = worldToLocal(vehicleNode, uX, uY, uZ);
if dz > 0 and math.abs(dx) < maxDx then
return i, true
end
end
end
CpUtil.debugVehicle(CpDebug.DBG_COURSES, self.vehicle, 'Course: could not find next forward waypoint from vehicle position after %d', ix)
return ix, false
end
function Course:getNextRevWaypointIxFromVehiclePosition(ix, vehicleNode, lookAheadDistance)
for i = ix, #self.waypoints do
if self:isReverseAt(i) then
local uX, uY, uZ = self:getWaypointPosition(i)
local _, _, z = worldToLocal(vehicleNode, uX, uY, uZ);
if z < -lookAheadDistance then
return i
end
end
end
CpUtil.debugVehicle(CpDebug.DBG_COURSES, self.vehicle, 'Course: could not find next reverse waypoint from vehicle position after %d', ix)
return ix
end
--- Cut waypoints from the end of the course until we shortened it by at least d
-- @param d length in meters to shorten course
-- @return true if shortened
-- TODO: this must be protected from courses with a few waypoints only
function Course:shorten(d)
local dCut = 0
local from = #self.waypoints - 1
for i = from, 1, -1 do
dCut = dCut + self.waypoints[i].dToNext
if dCut > d then
self:enrichWaypointData()
return true
end
table.remove(self.waypoints)
end
self:enrichWaypointData()
return false
end
--- Append waypoints to the course
---@param waypoints Waypoint[]
function Course:appendWaypoints(waypoints)
for i = 1, #waypoints do
table.insert(self.waypoints, Waypoint(waypoints[i]))
end
self:enrichWaypointData()
end
--- Append another course to the course
---@param other Course
function Course:append(other)
self:appendWaypoints(other.waypoints)
end
--- Return a copy of the course
function Course:copy(vehicle, first, last)
local newCourse = Course(vehicle or self.vehicle, self.waypoints, self:isTemporary(), first, last)
newCourse:setName(self:getName())
newCourse.nVehicles = self.nVehicles
newCourse.workWidth = self.workWidth
newCourse.numberOfHeadlands = self.numberOfHeadlands
if self.nVehicles > 1 then
newCourse.multiVehicleData = self.multiVehicleData:copy()
end
return newCourse
end
--- Append a single waypoint to the course
---@param waypoint Waypoint
function Course:appendWaypoint(waypoint)
table.insert(self.waypoints, Waypoint(waypoint))
end
--- Extend a course with a straight segment (same direction as last WP)
---@param length number the length to extend the course with
---@param dx number direction to extend
---@param dz number direction to extend
function Course:extend(length, dx, dz)
-- remember the number of waypoints when we started
local nWaypoints = #self.waypoints
local lastWp = self.waypoints[#self.waypoints]
dx, dz = dx or lastWp.dx, dz or lastWp.dz
local step = 5
local first = math.min(length, step)
local last = length
for i = first, last, step do
local x = lastWp.x + dx * i
local z = lastWp.z + dz * i
self:appendWaypoint({ x = x, z = z, rev = lastWp.rev })
end
if length % step > 0 then
-- add the remainder to make sure we extend all the way up to length
local x = lastWp.x + dx * length
local z = lastWp.z + dz * length
self:appendWaypoint({ x = x, z = z, rev = lastWp.rev })
end
-- enrich the waypoints we added
self:enrichWaypointData(nWaypoints)
end
--- Reverse a course, that is, the last waypoint becomes the first and the first the last.
--- Row start/end and other attributes are flipped accordingly.
--- @see CourseGenerator.FieldworkCourse:reverse() and
--- @see CourseGenerator.WaypointAttributes:reverse()
function Course:reverse()
CourseGenerator.reverseArray(self.waypoints)
for _, p in ipairs(self.waypoints) do
p.attributes:_reverse()
end
self:enrichWaypointData()
CpUtil.debugVehicle(CpDebug.DBG_COURSES, self.vehicle, 'Course reversed')
end
--- Create a new (straight) temporary course based on a node
---@param vehicle table
---@param referenceNode number
---@param xOffset number side offset of the new course (relative to node), left positive
---@param from number start at this many meters z offset from node
---@param to number end at this many meters z offset from node
---@param step number step (waypoint distance), must be negative if to < from
---@param reverse boolean is this a reverse course?
function Course.createFromNode(vehicle, referenceNode, xOffset, from, to, step, reverse)
local waypoints = {}
-- never go under 0.5 m length, also protect from division by zero when from == to
local distance = math.max(math.abs(from - to), 0.5)
-- if the distance < step, reduce step to the distance, so we have at least two waypoints.
local nPoints = math.floor(distance / math.min(distance, math.abs(step))) + 1
local dBetweenPoints = (to - from) / (nPoints - 1)
local dz = from
for i = 0, nPoints - 1 do
local x, _, z = localToWorld(referenceNode, xOffset, 0, dz + i * dBetweenPoints)
table.insert(waypoints, { x = x, z = z, rev = reverse })
end
return Course(vehicle, waypoints, true)
end
--- Create a straight, forward course for the vehicle.
---@param vehicle table the course will start at the root node of the vehicle
---@param length number|nil optional length of the course in meters, default is 100 meters
---@param xOffset number|nil optional side offset for the course
---@param directionNode number|nil optional force direction node
function Course.createStraightForwardCourse(vehicle, length, xOffset, directionNode)
local l = length or 100
return Course.createFromNode(vehicle, directionNode or vehicle.rootNode, xOffset or 0, 0, l, 5, false)