This repository has been archived by the owner on May 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 528
/
course_management.lua
1851 lines (1619 loc) · 63.7 KB
/
course_management.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 curFile = 'course_management.lua';
local ceil = math.ceil;
-- saving // loading courses
function courseplay.courses:setup()
-- LOAD COURSES AND FOLDERS FROM XML
if g_currentMission.cp_courses == nil then
-- courseplay:debug("cp_courses was nil and initialized", courseplay.DBG_COURSES);
g_currentMission.cp_courses = {};
g_currentMission.cp_courseManager = {};
g_currentMission.cp_folders = {};
g_currentMission.cp_sorted = { item={}, info={} };
if g_server ~= nil and next(g_currentMission.cp_courses) == nil then
self:loadCoursesAndFoldersFromXml();
-- courseplay:debug(tableShow(g_currentMission.cp_courses, "g_cM cp_courses", 8), courseplay.DBG_COURSES);
end;
end;
end;
-- enables input for course/folder/filter name
function courseplay:showSaveCourseForm(vehicle, saveWhat) -- fn is in courseplay because it's vehicle based
--- Prevent form from locking up mouse and keyboard when closing it.
courseplay:lockContext(false);
--print(string.format("courseplay:showSaveCourseForm(vehicle(%s), saveWhat(%s))",tostring(vehicle),tostring(saveWhat)))
--print(string.format("vehicle.cp.imWriting(%s)",tostring(vehicle.cp.imWriting)))
saveWhat = saveWhat or 'course'
if saveWhat == 'course' then
if vehicle.cp.numWaypoints > 0 then
courseplay.vehicleToSaveCourseIn = vehicle;
if vehicle.cp.imWriting then
vehicle.cp.saveWhat = 'course'
g_gui:showGui("inputCourseNameDialogue");
vehicle.cp.imWriting = false
end
end;
elseif saveWhat == 'folder' then
courseplay.vehicleToSaveCourseIn = vehicle;
if vehicle.cp.imWriting then
vehicle.cp.saveWhat = 'folder'
g_gui:showGui("inputCourseNameDialogue");
vehicle.cp.imWriting = false
end
elseif saveWhat == 'filter' then
if vehicle.cp.hud.filter == '' then
courseplay.vehicleToSaveCourseIn = vehicle;
if vehicle.cp.imWriting then
vehicle.cp.saveWhat = 'filter';
g_gui:showGui("inputCourseNameDialogue");
vehicle.cp.imWriting = false;
end;
else
vehicle.cp.hud.filter = '';
vehicle.cp.hud.filterButton:setSpriteSectionUVs('search');
vehicle.cp.hud.filterButton:setToolTip(courseplay:loc('COURSEPLAY_SEARCH_FOR_COURSES_AND_FOLDERS'));
courseplay.settings.setReloadCourseItems(vehicle);
end;
end
end;
function courseplay:reloadCourses(vehicle, useRealId) -- fn is in courseplay because it's vehicle based
courseplay:debug(('%s: reloadCourses(..., %s)'):format(nameNum(vehicle), tostring(useRealId)), courseplay.DBG_COURSES);
local courses = vehicle.cp.loadedCourses;
vehicle.cp.loadedCourses = {};
for k, v in pairs(courses) do
courseplay:loadCourse(vehicle, v, useRealId);
end;
end;
function courseplay.courses:reinitializeCourses()
if g_currentMission.cp_courses == nil then
courseplay:debug("cp_courses is empty", courseplay.DBG_COURSES)
if g_server ~= nil then
self:loadCoursesAndFoldersFromXml();
end
return
end
end
function courseplay:addSortedCourse(vehicle, index) -- fn is in courseplay because it's vehicle based
local id = vehicle.cp.hud.courses[index].id
courseplay:loadCourse(vehicle, id, true, true)
end
function courseplay:loadSortedCourse(vehicle, index) -- fn is in courseplay because it's vehicle based
if type(vehicle.cp.hud.courses[index]) ~= nil then
local id = vehicle.cp.hud.courses[index].id
courseplay:loadCourse(vehicle, id, true)
end
end
function courseplay:loadCourse(vehicle, id, useRealId, addCourseAtEnd) -- fn is in courseplay because it's vehicle based
-- global array for courses, no refreshing needed any more
courseplay.courses:reinitializeCourses();
if addCourseAtEnd == nil then addCourseAtEnd = false; end;
courseplay:debug(string.format('%s: loadCourse(..., id=%s, useRealId=%s, addCourseAtEnd=%s)', nameNum(vehicle), tostring(id), tostring(useRealId), tostring(addCourseAtEnd)), courseplay.DBG_COURSES);
if id ~= nil and id ~= "" then
if not useRealId then
-- this useRealId smells to heaven...
return -- not supported any more
end
id = id * 1 -- equivalent to tonumber()
-- negative values mean that addCourseAtEnd is true
if id < 1 then
id = id * -1
addCourseAtEnd = true;
end
if not g_currentMission.cp_courses[id] then
courseplay.infoVehicle(vehicle, 'There is no course with id=%d, not loading course for this vehicle', id)
return
end
if not g_currentMission.cp_courses[id].waypoints and not g_currentMission.cp_courses[id].virtual then
if not CpManager.isMP or not courseplay.isClient then
courseplay.debugVehicle(courseplay.DBG_COURSES, vehicle, 'Loading course %d (%s)', id, g_currentMission.cp_courses[id].nameClean)
courseplay.courses:loadCourseFromFile(g_currentMission.cp_courses[id])
else
g_currentMission.cp_courses[id].waypoints = {}
end
end
local course
if g_currentMission.cp_courses[id].virtual then
course = courseplay.courses:loadAutoDriveCourse(vehicle, g_currentMission.cp_courses[id])
else
course = g_currentMission.cp_courses[id]
end
if course == nil then
courseplay.infoVehicle(vehicle, 'id %d -> course not found, return', id)
return
end
if addCourseAtEnd == true then
table.insert(vehicle.cp.loadedCourses, id * -1)
else
table.insert(vehicle.cp.loadedCourses, id)
end
-- courseplay:clearCurrentLoadedCourse(vehicle)
if #vehicle.Waypoints == 0 then
vehicle.cp.numCourses = 1;
vehicle.Waypoints = course.waypoints
vehicle.cp.numWayPoints = #vehicle.Waypoints;
vehicle.cp.currentCourseName = course.name
-- for turn maneuver
vehicle.cp.courseWorkWidth = course.workWidth;
vehicle.cp.courseNumHeadlandLanes = course.numHeadlandLanes;
vehicle.cp.courseHeadlandDirectionCW = course.headlandDirectionCW;
course.multiTools = course.multiTools or 1
vehicle.cp.courseGeneratorSettings.multiTools:set(course.multiTools)
courseplay:debug(string.format("course_management %d: %s: no course was loaded -> new course = course -> currentCourseName=%q, numCourses=%s",
debug.getinfo(1).currentline, nameNum(vehicle), tostring(vehicle.cp.currentCourseName),
tostring(vehicle.cp.numCourses)), courseplay.DBG_COURSES);
else -- add new course to old course
if vehicle.cp.currentCourseName == nil then --recorded but not saved course
vehicle.cp.numCourses = 1;
end;
courseplay:debug(string.format("course_management %d: %s: currentCourseName=%q, numCourses=%s -> add new course %q",
debug.getinfo(1).currentline, nameNum(vehicle), tostring(vehicle.cp.currentCourseName),
tostring(vehicle.cp.numCourses), tostring(course.name)), courseplay.DBG_COURSES);
local course1, course2 = vehicle.Waypoints, course.waypoints;
local numCourse1, numCourse2 = #course1, #course2;
local course1wp, course2wp = numCourse1, 1;
local matchFound = false
local wpDistMax = 50
-- may cause problems when intesections are too close to one another - think town @Golcrest
--find crossing points, merge at first pair where dist < wpDistMax
if not addCourseAtEnd then
--find crossing points
local crossingPoints = { [1] = {}, [2] = {} };
for i=vehicle.cp.lastMergedWP + 1, numCourse1 do
if i > 1 and course1[i].crossing == true and not course1[i].merged then
courseplay:debug('course1 wp ' .. i .. ': add to crossingPoints[1]', courseplay.DBG_COURSES);
table.insert(crossingPoints[1], i);
end;
end;
for i,wp in pairs(course2) do
if i < numCourse2 and wp.crossing == true and not wp.merged then
courseplay:debug('course2 wp ' .. i .. ': add to crossingPoints[2]', courseplay.DBG_COURSES);
table.insert(crossingPoints[2], i);
end;
end;
courseplay:debug(string.format('course 1 has %d crossing points (excluding first point), course 2 has %d crossing points (excluding last point), useFirstMatch=%s', #crossingPoints[1], #crossingPoints[2], tostring(useFirstMatch)), courseplay.DBG_COURSES);
--find < wpDistMax match with lowest total turn angle
local smallestAngle, smallestDist = math.huge, math.huge;
if #crossingPoints[1] > 0 and #crossingPoints[2] > 0 then
for _,wpNum1 in pairs(crossingPoints[1]) do
local wp1 = course1[wpNum1];
for _,wpNum2 in pairs(crossingPoints[2]) do
local wp2 = course2[wpNum2];
local x1, z1, x2, z2 = wp1.cx or wp1.x, wp1.cz or wp1.z, wp2.cx or wp2.x, wp2.cz or wp2.z
local dist = courseplay:distance(x1, z1, x2, z2);
--Calculate actual turn direction between pair of crosspoints
local angleTurn = math.atan2(x2 - x1, z2 - z1) -- in radians
--add direction change differences between original direction and turn direction and destination direction
local totalAngle=math.deg(
math.abs(getDeltaAngle(math.rad(wp1.angle),angleTurn)) +
math.abs(getDeltaAngle(angleTurn,math.rad(wp2.angle))))
angleTurn = math.deg(angleTurn) -- now in degrees
--courseplay:debug(string.format('course1 wp %d, course2 wp %d, dist=%s', wpNum1, wpNum2, tostring(dist)), courseplay.DBG_COURSES);
if dist and dist ~= 0 and dist < wpDistMax then
courseplay:debug(string.format('wp1 %d %.2f° wp2 %d %.2f° dist=%.1f angleTurn %.2f°, totalAngle %.2f°, lowA %.2f°, lowD %.1f',
wpNum1, wp1.angle, wpNum2, wp2.angle, dist, angleTurn , totalAngle, smallestAngle, smallestDist), courseplay.DBG_COURSES);
local foundBetter = false
--better is when totalAngle is significantly better than before (say 10 degrees)
if totalAngle + 10 < smallestAngle then
smallestAngle = totalAngle;
foundBetter = true
smallestDist = dist -- this is now the distance to beat
end
-- or when totalAngle is relatively the same - within 10 degrees - but distance is shorter
if (totalAngle - 10 < smallestAngle) and (dist < smallestDist) then
foundBetter = true
smallestDist = dist --distance just got better
end
if foundBetter then
matchFound = true
--remove previous 'merged' vars
course1[course1wp].merged = nil;
course2[course2wp].merged = nil;
course1wp = wpNum1;
course2wp = wpNum2;
vehicle.cp.lastMergedWP = wpNum1;
course1[course1wp].merged = true;
course2[course2wp].merged = true;
courseplay.debugVehicle(courseplay.DBG_COURSES, vehicle,
'wp1 %d %.2f° wp2 %d %.2f° dist=%.1f angleTurn %.2f°, totalAngle %.2f°, lowA %.2f°, lowD %.1f',
wpNum1, wp1.angle, wpNum2, wp2.angle, dist, angleTurn , totalAngle, smallestAngle, smallestDist)
end;
end;
end;
end;
end;
if matchFound then
courseplay:debug(string.format('%s: merge points found: course 1: #%d, course 2: #%d',
nameNum(vehicle), course1wp, course2wp), 8);
else
courseplay:debug(string.format('%s: no points where the courses could be merged have been found -> add 2nd course at end',
nameNum(vehicle)), 8);
end
end;
vehicle.Waypoints = {};
for i=1, course1wp do
table.insert(vehicle.Waypoints, course1[i]);
end;
for i=course2wp, numCourse2 do
table.insert(vehicle.Waypoints, course2[i]);
end;
vehicle.cp.numWayPoints = #vehicle.Waypoints;
vehicle.cp.numCourses = vehicle.cp.numCourses + 1;
vehicle.cp.currentCourseName = string.format("%d %s", vehicle.cp.numCourses, courseplay:loc('COURSEPLAY_COMBINED_COURSES'))
-- for turn maneuver
if not vehicle.cp.courseWorkWidth then
vehicle.cp.courseWorkWidth = course.workWidth;
--Place here to prevent it being reset back to one multi Tool on course addition when course isn't auto generated
course.multiTools = course.multiTools or 1
vehicle.cp.courseGeneratorSettings.multiTools:set(course.multiTools)
end;
if not vehicle.cp.courseNumHeadlandLanes then
vehicle.cp.courseNumHeadlandLanes = course.numHeadlandLanes;
end;
if vehicle.cp.courseHeadlandDirectionCW == nil then
vehicle.cp.courseHeadlandDirectionCW = course.headlandDirectionCW;
end;
courseplay:debug(string.format('%s: adding course done -> numWaypoints=%d, numCourses=%s, currentCourseName=%q', nameNum(vehicle), vehicle.cp.numWaypoints, vehicle.cp.numCourses, vehicle.cp.currentCourseName), courseplay.DBG_COURSES);
end;
vehicle:setCpVar('canDrive',true,courseplay.isClient);
courseplay:setWaypointIndex(vehicle, 1);
courseplay.signs:updateWaypointSigns(vehicle, "current");
vehicle.cp.hasGeneratedCourse = false;
courseplay:validateCanSwitchMode(vehicle);
-- SETUP 2D COURSE DRAW DATA
vehicle.cp.course2dUpdateDrawData = true;
courseplay.hud:setReloadPageOrder(vehicle, vehicle.cp.hud.currentPage, true)
if CpManager.isMP and g_server ~= nil then
CourseEvent.sendEvent(vehicle,vehicle.Waypoints)
end
end
end
function courseplay:copyCourse(vehicle)
if vehicle.cp.hasFoundCopyDriver ~= nil and vehicle.cp.copyCourseFromDriver ~= nil then
local src = vehicle.cp.copyCourseFromDriver;
vehicle.Waypoints = src.Waypoints;
vehicle.cp.currentCourseName = src.cp.currentCourseName
vehicle.cp.loadedCourses = src.cp.loadedCourses;
vehicle.cp.numCourses = src.cp.numCourses;
courseplay:setWaypointIndex(vehicle, 1);
vehicle.cp.numWayPoints = #vehicle.Waypoints;
vehicle.cp.numWaitPoints = src.cp.numWaitPoints;
vehicle.cp.numCrossingPoints = src.cp.numCrossingPoints;
vehicle.cp.courseNumHeadlandLanes = src.cp.courseNumHeadlandLanes
vehicle.cp.courseHeadlandDirectionCW = src.cp.courseHeadlandDirectionCW
courseplay:setIsRecording(vehicle, false);
courseplay:setRecordingIsPaused(vehicle, false);
vehicle:setIsCourseplayDriving(false);
vehicle:setCpVar('distanceCheck',false,courseplay.isClient);
vehicle:setCpVar('canDrive',true,courseplay.isClient);
if src.cp.settings.searchCombineOnField:get() >0 then
vehicle.cp.settings.searchCombineOnField:set(src.cp.settings.searchCombineOnField:get())
end
vehicle.cp.curTarget.x, vehicle.cp.curTarget.y, vehicle.cp.curTarget.z ,vehicle.cp.curTarget.rev = nil, nil, nil, nil;
vehicle.cp.nextTargets = {};
vehicle.cp.recordingTimer = 1;
courseplay.signs:updateWaypointSigns(vehicle, 'current');
--reset variables
vehicle.cp.selectedDriverNumber = 0;
vehicle.cp.hasFoundCopyDriver = false;
vehicle.cp.copyCourseFromDriver = nil;
--MultiTools
if src.cp.courseGeneratorSettings.multiTools:get() > 1 then
vehicle.cp.courseWorkWidth = src.cp.courseWorkWidth
vehicle.cp.courseGeneratorSettings.multiTools:set(src.cp.courseGeneratorSettings.multiTools:get())
else
vehicle.cp.courseGeneratorSettings.multiTools:set(1)
end;
courseplay:validateCanSwitchMode(vehicle);
-- SETUP 2D COURSE DRAW DATA
vehicle.cp.course2dUpdateDrawData = true;
end;
end;
-- clears current course -- just setting variables
function courseplay:clearCurrentLoadedCourse(vehicle)
if vehicle.cp.settings.searchCombineOnField:get() > 0 then
vehicle.cp.settings.searchCombineOnField:set(0);
end
-------------------------------------------------------
courseplay.courses:resetMerged();
courseplay:setWaypointIndex(vehicle, 1,true);
vehicle.cp.curTarget.x, vehicle.cp.curTarget.y, vehicle.cp.curTarget.z = nil, nil, nil;
vehicle.cp.nextTargets = {};
vehicle.cp.loadedCourses = {}
vehicle.cp.currentCourseName = nil
vehicle.cp.recordingTimer = 1;
vehicle.Waypoints = {}
vehicle:setCpVar('canDrive',false,courseplay.isClient);
courseplay:resetTipTrigger(vehicle);
vehicle.cp.lastMergedWP = 1;
vehicle.cp.numCourses = 0;
vehicle.cp.numWaypoints = 0;
vehicle.cp.numWaitPoints = 0;
vehicle.cp.waitPoints = {};
-- for turn maneuver
vehicle.cp.courseWorkWidth = nil;
vehicle.cp.courseNumHeadlandLanes = nil;
vehicle.cp.courseHeadlandDirectionCW = nil;
vehicle.cp.hasGeneratedCourse = false;
courseplay:validateCanSwitchMode(vehicle);
courseplay.signs:updateWaypointSigns(vehicle, "current");
vehicle.cp.hud.clearCurrentCourseButton:setHovered(false);
courseplay.hud:setReloadPageOrder(vehicle, vehicle.cp.hud.currentPage, true);
-- remove 2D course data
vehicle.cp.course2dDimensions = nil;
vehicle.cp.course2dDrawData = nil;
vehicle.cp.course2dBackground = nil;
end;
function courseplay.courses:sort(courses_to_sort, folders_to_sort, parent_id, level, make_copies)
--Note: this function is recursive.
courses_to_sort = courses_to_sort or g_currentMission.cp_courses
folders_to_sort = folders_to_sort or g_currentMission.cp_folders
parent_id = parent_id or 0
level = level or 0
if make_copies == nil then
make_copies = true
end
if make_copies then
-- Tables are pointers. The sort function will delete entries in the tables. In order to preserve the original tables a copy is made in the first execution.
-- note that only courses_to_sort and folders_to_sort are copied. if those contain tables themselves again, these tables are referenced again (the reference is copied).
courses_to_sort = courseplay.utils.table.copy(courses_to_sort)
folders_to_sort = courseplay.utils.table.copy(folders_to_sort)
end
local sorted = {}
sorted.item = {}
sorted.info = {}
local last_child = 0
-- search for folder children with this parent
local folders = {}
local temp_sorted, temp_sorted_items, temp_last_child
folders = courseplay.utils.table.search_in_field(folders_to_sort, 'parent', parent_id)
table.sort(folders, courseplay.utils.table.compare_name)
-- search for course children with this parent
local courses = {}
courses = courseplay.utils.table.search_in_field(courses_to_sort, 'parent', parent_id)
table.sort(courses, courseplay.utils.table.compare_name)
-- handle the folders first
-- first delete the found entries in the folders_to_sort
-- this has to be done in a separate loop as folders_to_sort is used in the loop and should then not contain the already found folders anymore.
for i = 1, #folders do
folders_to_sort[folders[i].id] = nil
end
for i = 1, #folders do
-- find child's children
temp_sorted, temp_last_child = self:sort(courses_to_sort, folders_to_sort, folders[i].id, level+1, false)
temp_sorted_items = temp_sorted.item
folders[i].level = level
folders[i].displayname = folders[i].name
sorted.info[ folders[i].uid ] = {}
if #courses ~= 0 or i ~= #folders then
-- there are courses after the last folder or it's not the last folder
sorted.info[ folders[i].uid ].next_neighbour = #temp_sorted_items + 1 -- relative index to next neighbour
else
-- it's the last folder and there are no courses afterwards
sorted.info[folders[i].uid].next_neighbour = 0
end
sorted.info[folders[i].uid].lastChild = temp_last_child -- relative index to the last direct child
sorted.info[folders[i].uid].parent_ridx = -(#sorted.item + 1) -- relative index to the parent
if i > 1 then
sorted.info[folders[i].uid].leading_neighbour = -sorted.info[folders[i-1].uid].next_neighbour -- relative index to the leading neighbour
else
sorted.info[folders[i].uid].leading_neighbour = 0
end
-- append folder
table.insert(sorted.item, folders[i])
-- append children
sorted.item = courseplay.utils.table.append(sorted.item, temp_sorted_items)
-- add children's info
sorted.info = courseplay.utils.table.merge(sorted.info, temp_sorted.info)
end
-- now handle the found courses:
for i = 1, #courses do
-- first delete the course form courses_to_sort
courses_to_sort[courses[i].id] = nil
courses[i].level = level
courses[i].displayname = courses[i].name
sorted.info[ courses[i].uid ] = {}
if i ~= #courses then
-- it's not the last entry
sorted.info[courses[i].uid].next_neighbour = 1
else
sorted.info[courses[i].uid].next_neighbour = 0
end
sorted.info[courses[i].uid].parent_ridx = -(#sorted.item + 1)
if i ~= 1 then
-- it's not the first course, so there is one before
sorted.info[courses[i].uid].leading_neighbour = -1
elseif #folders ~= 0 then
-- it is the first course, but there are folders before
sorted.info[courses[i].uid].leading_neighbour = -(#temp_sorted_items + 1)
else
-- first course and no folders, so it is the very first one
sorted.info[courses[i].uid].leading_neighbour = 0
end
table.insert(sorted.item, courses[i])
end
if #courses > 0 then
last_child = #(sorted.item) -- relative index to the last direct child
elseif #folders > 0 then
last_child = #(sorted.item) - #temp_sorted_items
else
last_child = 0
end
if level == 0 then
-- all courses and folders should be handled now (we are done)
local n = #sorted.item
for i=1, n do
sorted.info[ sorted.item[i].uid ].sorted_index = i
end
-- are we really done? -> add any corrupted folders and courses:
for k,v in pairs(folders_to_sort) do
v.level = level
v.displayname = v.name .. ' (corrupted)'
table.insert(sorted.item, v)
end
for k,v in pairs(courses_to_sort) do
v.level = level
v.displayname = v.name .. ' (corrupted)'
table.insert(sorted.item, v)
end
for i = n+1, #sorted.item do
sorted.info[ sorted.item[i].uid ] = {sorted_index=i}
end
end
return sorted, last_child
end
function courseplay.courses:resetMerged()
for _,course in pairs(g_currentMission.cp_courses) do
if course.waypoints then
for num, wp in pairs(course.waypoints) do
wp.merged = nil;
end;
end;
end;
end
function courseplay:deleteSortedItem(vehicle, index) -- fn is in courseplay because it's vehicle based
local id = vehicle.cp.hud.courses[index].id
local type = vehicle.cp.hud.courses[index].type
if type == 'course' then
local slotId = self.courses:getFreeSaveSlot(id);
self.courses:removeFromManagerXml(type, slotId);
g_currentMission.cp_courses[id] = nil
elseif type == 'folder' then
-- check for children: delete only if folder has no children
if g_currentMission.cp_sorted.info['f'..id].lastChild == 0 then
self.courses:removeFromManagerXml(type, id);
self.courses:removeFolder(id)
end
else
--Error?!
end
g_currentMission.cp_sorted = courseplay.courses:sort()
courseplay.settings.setReloadCourseItems()
courseplay.signs:updateWaypointSigns(vehicle);
end
function courseplay.courses:saveFolderToXml(folder_id, cpCManXml, append)
-- Only runs for server
if g_server == nil then
return
end
-- saves a folder to the courseplay xml file
--
-- append (bool,integer): append can be a bool or an integer
-- if it's false, the function will check if the id exists in the file. if it exists, it will overwrite it otherwise it will append
-- if append is true, the function will search for the next free position and save there
-- if append is an integer, the function will save at this position (without checking if it is the end or what there was before)
local deleteFile = false
if append == nil then
append = false -- slow but secure
end
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML()
deleteFile = true
end
-- { id = id, type = 'folder', name = name, parent = parent }
local types = { id = 'Int', name = 'String', parent = 'Int'}
local i = 0
-- find the node position and save the attributes
if append ~= false then
if append == true then
i = courseplay.utils.findFreeXMLNode(cpCManXml,'courseManager.folders.folder')
else
i = append
end
else
i = courseplay.utils.findXMLNodeByAttr(cpCManXml, 'courseManager.folders.folder', 'id', folder_id, 'Int')
if i < 0 then i = -i end
end
courseplay.utils.setMultipleXML(cpCManXml, string.format('courseManager.folders.folder(%d)', i), g_currentMission.cp_folders[folder_id], types)
saveXMLFile(cpCManXml)
if deleteFile then
delete(cpCManXml)
end
end
function courseplay.courses:saveFoldersToXml(cpCManXml)
-- Only runs for server
if g_server == nil then
return
end
-- function to save all folders by once
local deleteFile = false;
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML();
deleteFile = true;
end;
local index = 0;
for k, folder in pairs(g_currentMission.cp_folders) do
if not folder.virtual then
self:saveFolderToXml(k, cpCManXml, index);
end
index = index + 1;
end;
if deleteFile then
delete(cpCManXml);
end;
end
function courseplay.courses:getFreeSaveSlot(course_id)
-- Only runs for server
if g_server == nil then
return nil, nil
end
local freeSlot = 1;
local isOwnSaveSlot = false;
-- Check if there is any saved data already. If not, we returns 1 as the firstSlot
if g_currentMission.cp_courseManager and #g_currentMission.cp_courseManager > 0 then
local foundFreeSlot = false;
-- Check if we already have an saved slot
if course_id then
for index, v in ipairs(g_currentMission.cp_courseManager) do
if v.id == course_id then
freeSlot = index;
foundFreeSlot = true;
isOwnSaveSlot = true;
end;
end;
end;
-- Check if there is an free slot we can use, in case we don't have one already.
if not foundFreeSlot then
for index, v in ipairs(g_currentMission.cp_courseManager) do
if v.isUsed == false then
freeSlot = index;
foundFreeSlot = true;
end;
end;
end;
-- If there were no free slot found, return the end position
if not foundFreeSlot then
freeSlot = #g_currentMission.cp_courseManager + 1;
end;
end;
return freeSlot, isOwnSaveSlot;
end
function courseplay.courses:writeCourseFile(courseXmlFilePath, cp_course)
local courseXml = createXMLFile("courseXml", courseXmlFilePath, 'course');
if cp_course.workWidth then
setXMLFloat(courseXml, "course#workWidth", cp_course.workWidth);
end;
if cp_course.numHeadlandLanes then
setXMLInt(courseXml, "course#numHeadlandLanes", cp_course.numHeadlandLanes);
end;
if cp_course.headlandDirectionCW ~= nil then
setXMLBool(courseXml, "course#headlandDirectionCW", cp_course.headlandDirectionCW);
end;
if cp_course.multiTools ~= nil then
setXMLInt(courseXml, "course#multiTools", cp_course.multiTools);
end;
-- always use the new waypoint format
setXMLInt(courseXml, "course#version", 2)
if courseXml and courseXml ~= 0 then
setXMLString(courseXml, 'course.waypoints', Course.serializeWaypoints(cp_course.waypoints))
saveXMLFile(courseXml);
delete(courseXml);
courseplay.debugFormat(courseplay.DBG_COURSES, 'Waypoints saved for course %s', cp_course.nameClean)
return true
else
delete(courseXml);
return false
end;
end
function courseplay.courses:saveCourseToXml(course_id, cpCManXml, forceCourseSave)
-- save course to xml file
if g_server == nil then
return
end
local deleteFile = false
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML()
deleteFile = true
end
local cp_course = g_currentMission.cp_courses[course_id];
local freeSlot, isOwnSaveSlot = self:getFreeSaveSlot(course_id);
-- We can use an unused slot
if g_currentMission.cp_courseManager[freeSlot] then
g_currentMission.cp_courseManager[freeSlot].isUsed = true;
g_currentMission.cp_courseManager[freeSlot].id = cp_course.id;
g_currentMission.cp_courseManager[freeSlot].name = cp_course.name;
g_currentMission.cp_courseManager[freeSlot].parent = cp_course.parent;
-- We are an new slot
else
local info = {
index = freeSlot - 1;
isUsed = true;
fileName = (CpManager.cpCourseStorageXmlFileTemplate):format(freeSlot);
id = cp_course.id;
name = cp_course.name;
parent = cp_course.parent;
}
table.insert(g_currentMission.cp_courseManager, info);
end;
self:updateCourseManagerSlotsXml(freeSlot, cpCManXml);
-- Dont save course if we already have a saveSlot.
if not isOwnSaveSlot or forceCourseSave then
local courseXmlFilePath = CpManager.cpCoursesFolderPath .. g_currentMission.cp_courseManager[freeSlot].fileName;
if not self:writeCourseFile(courseXmlFilePath, cp_course) then
print(("COURSEPLAY ERROR: Could not save course to file: %q"):format(courseXmlFilePath));
g_currentMission.cp_courseManager[freeSlot].isUsed = false;
self:updateCourseManagerSlotsXml(freeSlot, cpCManXml);
end
end;
saveXMLFile(cpCManXml)
if deleteFile then
delete(cpCManXml)
end
end
function courseplay.courses:saveCoursesToXml(cpCManXml)
-- Only runs for server
if g_server == nil then
return
end
-- function to save or update all courses by once
local deleteFile = false;
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML();
deleteFile = true;
end;
for k,_ in pairs(g_currentMission.cp_courses) do
self:saveCourseToXml(k, cpCManXml)
end
if deleteFile then
delete(cpCManXml);
end;
end
function courseplay.courses:saveAllToXml(cpCManXml)
-- saves or update all the courses and folders
if g_server == nil then
return;
end;
local deleteFile = false;
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML();
deleteFile = true;
end;
self:saveFoldersToXml(cpCManXml);
self:saveCoursesToXml(cpCManXml);
if deleteFile then
delete(cpCManXml)
end
end
function courseplay.courses:removeFromManagerXml(type, type_id, cpCManXml)
-- Only runs for server
if g_server == nil then
return
end
local deleteFile = false;
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML();
deleteFile = true;
end;
local key = "";
if type == "course" and type_id and type_id > 0 and type_id <= #g_currentMission.cp_courseManager then
key = ("courseManager.saveSlot.slot(%d)"):format(g_currentMission.cp_courseManager[type_id].index);
-- Set isUsed to false, so it can be used again later.
setXMLBool(cpCManXml, key .. '#isUsed', false);
g_currentMission.cp_courseManager[type_id].isUsed = false;
-- Remove values that's not needed anymore
if hasXMLProperty(cpCManXml, key .. "#id") then removeXMLProperty(cpCManXml, key .. "#id"); end;
if hasXMLProperty(cpCManXml, key .. "#name") then removeXMLProperty(cpCManXml, key .. "#name"); end;
if hasXMLProperty(cpCManXml, key .. "#parent") then removeXMLProperty(cpCManXml, key .. "#parent"); end;
g_currentMission.cp_courseManager[type_id].id = nil;
g_currentMission.cp_courseManager[type_id].name = nil;
g_currentMission.cp_courseManager[type_id].parent = nil;
-- Clear the courseStorage file for unused data.
local courseXmlFilePath = CpManager.cpCoursesFolderPath .. g_currentMission.cp_courseManager[type_id].fileName;
if fileExists(courseXmlFilePath) then
local courseXml = createXMLFile("courseXml", courseXmlFilePath, 'course');
saveXMLFile(courseXml);
delete(courseXml);
end;
elseif type == "folder" then
key = "courseManager.folders.folder";
local id = courseplay.utils.findXMLNodeByAttr(cpCManXml, key, 'id', type_id, 'Int')
if id >= 0 then
removeXMLProperty(cpCManXml, key .. ("(%d)"):format(id));
end;
end;
saveXMLFile(cpCManXml)
if deleteFile then
delete(cpCManXml)
end
end
function courseplay.courses:updateCourseManagerSlotsXml(slot, cpCManXml)
-- Only runs for server
if g_server == nil then
return
end
local deleteFile = false;
if cpCManXml == nil then
cpCManXml = self:getCourseManagerXML();
deleteFile = true;
end;
if g_currentMission.cp_courseManager[slot].isUsed then
local types = {
isUsed = 'Bool',
fileName = 'String',
id = 'Int',
name = 'String',
parent = 'Int'
};
courseplay.utils.setMultipleXML(cpCManXml, string.format('courseManager.saveSlot.slot(%d)', g_currentMission.cp_courseManager[slot].index), g_currentMission.cp_courseManager[slot], types)
else
self.removeFromManagerXml("course", slot, cpCManXml);
end;
saveXMLFile(cpCManXml)
if deleteFile then
delete(cpCManXml)
end
end
function courseplay.courses:getCourseManagerXML()
-- Only runs for server
if g_server == nil then
return
end
-- returns the file if success, nil else
local cpCManXml;
local filePath = CpManager.cpCourseManagerXmlFilePath;
if filePath ~= nil then
if fileExists(filePath) then
cpCManXml = loadXMLFile("courseManagerXml", filePath)
else
cpCManXml = createXMLFile("courseManagerXml", filePath, 'courseManager')
end
else
--this is a problem...
-- File stays nil
end
return cpCManXml
end
function courseplay.courses:getMaxCourseID()
local maxID = 0
if g_currentMission.cp_courses ~= nil then
for _, course in pairs(g_currentMission.cp_courses) do
if not course.virtual and course.id > maxID then
maxID = course.id
end
end
end
return maxID
end
-- sometimes we return nil, sometimes false, no idea why
function courseplay.courses:getMaxFolderID()
local maxID;
if g_currentMission.cp_folders ~= nil then
maxID = courseplay.utils.table.getMax(g_currentMission.cp_folders, 'id')
if maxID == false then
maxID = 0
end
end
return maxID
end
function courseplay:linkParent(vehicle, index)
if type(vehicle.cp.hud.courses[index]) ~= nil then
local id = vehicle.cp.hud.courses[index].id
local type = vehicle.cp.hud.courses[index].type
if vehicle.cp.hud.choose_parent ~= true then
vehicle.cp.hud.selected_child = { type = type, id = id }
-- show folders:
vehicle.cp.hud.showFoldersOnly = true
vehicle.cp.hud.showZeroLevelFolder = true
courseplay.settings.toggleFilter(vehicle, false);
if type == 'folder' then
vehicle.cp.folder_settings[id].skipMe = true
end
courseplay.hud.setCourses(vehicle,1)
vehicle.cp.hud.choose_parent = true
else -- choose_parent is true
-- prepare showing courses:
vehicle.cp.hud.showFoldersOnly = false
vehicle.cp.hud.showZeroLevelFolder = false
courseplay.settings.toggleFilter(vehicle, true);
if vehicle.cp.hud.selected_child.type == 'folder' then
vehicle.cp.folder_settings[vehicle.cp.hud.selected_child.id].skipMe = false
end
vehicle.cp.hud.choose_parent = false
-- link if possible and show courses anyway
if type == 'folder' then --parent must be a folder!
if vehicle.cp.hud.selected_child.type == 'folder' then
g_currentMission.cp_folders[vehicle.cp.hud.selected_child.id].parent = id
courseplay.courses:saveFolderToXml(vehicle.cp.hud.selected_child.id)
else
g_currentMission.cp_courses[vehicle.cp.hud.selected_child.id].parent = id
courseplay.courses:saveCourseToXml(vehicle.cp.hud.selected_child.id)
end
g_currentMission.cp_sorted = courseplay.courses:sort()
courseplay.settings.setReloadCourseItems()
else
courseplay.hud.setCourses(vehicle,1)
end
end -- if choose parent
else
-- type(vehicle.cp.hud.courses[index]) == nil
if vehicle.cp.hud.choose_parent then
print('folder not available')
-- maybe there are no folders?
-- go back
vehicle.cp.hud.showFoldersOnly = false
vehicle.cp.hud.showZeroLevelFolder = false
courseplay.settings.toggleFilter(vehicle, true);
if vehicle.cp.hud.selected_child.type == 'folder' then
vehicle.cp.folder_settings[vehicle.cp.hud.selected_child.id].skipMe = false
end
courseplay.hud.setCourses(vehicle,1)