-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathformgps_position.cpp
More file actions
2284 lines (1864 loc) · 98.8 KB
/
formgps_position.cpp
File metadata and controls
2284 lines (1864 loc) · 98.8 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
// Copyright (C) 2024 Michael Torrie and the QtAgOpenGPS Dev Team
// SPDX-License-Identifier: GNU General Public License v3.0 or later
//
// This runs every time we get a new GPS fix, or sim position
#include "formgps.h"
#include "cnmea.h"
#include "modulecomm.h"
#include "ccontour.h"
#include "cvehicle.h"
#include "csection.h"
#include "cboundary.h"
#include "ctrack.h"
#include "settingsmanager.h"
#include <QQuickView>
#include <QOpenGLContext>
#include <QPair>
#include <QElapsedTimer>
#include <QLabel>
#include <QPainter>
#include "glm.h"
#include "aogrenderer.h"
#include "cpgn.h"
#include "qmlutil.h"
#include "glutils.h"
#include "rendering.h"
#include "backend.h"
#include "mainwindowstate.h"
#include "boundaryinterface.h"
#include "recordedpath.h"
#include "siminterface.h"
#include "modulecomm.h"
#include "cpgn.h"
#include "blockage.h"
#include "ratecontrol.h"
#include "tools.h"
#include "steerconfig.h"
#include "backendaccess.h"
#include "camera.h"
#include "vehicleproperties.h"
#include "sectionproperties.h"
#include "layerservice.h"
#include <QtConcurrent/QtConcurrentRun>
Q_LOGGING_CATEGORY (qpos, "formgps_position.qtagopengps")
extern QLabel *grnPixelsWindow;
extern QLabel *overlapPixelsWindow;
inline QColor QColorWithAlpha(const QColor &c, int a) {
return QColor(c.red(), c.green(), c.blue(), a);
}
//called for every new GPS or simulator position
void FormGPS::UpdateFixPosition()
{
QLocale locale;
CNMEA &pn = *Backend::instance()->pn();
BACKEND_TRACK(track); //bring in a reference "track"
CContour &ct = track.contour;
BACKEND_YT(yt); //bring in a reference "yt"
Camera &camera = *Camera::instance();
// PHASE 6.0.33: Declare rawGpsPosition at function start (before goto labels)
// Used to separate RAW GPS positions (for heading calc) from CORRECTED positions (for display)
// Now copies from m_rawGpsPosition member (set by onNmeaDataReady at 8 Hz)
Vec2 rawGpsPosition;
CPGN_FE &p_254 = ModuleComm::instance()->p_254;
//swFrame.Stop();
//Measure the frequency of the GPS updates
//timeSliceOfLastFix = (double)(swFrame.elapsed()) / 1000;
qDebug(qpos) << "swFrame time at new frame: " << swFrame.elapsed();
//lock.lockForWrite(); //stop GL from updating while we calculate a new position
// Phase 6.0.21: Calculate Hz from CPU timer (AgIOService.nowHz/gpsHz removed)
// GPS frequency is calculated from frame timing
nowHz = 1000.0 / swFrame.elapsed(); //convert ms into hz
// Phase 6.0.20 Task 24 Step 5.6: Remove artificial 20 Hz ceiling in simulation mode
// - Simulation mode: Show real CPU performance (can be 50+ Hz)
// - Real mode fallback: Apply limits only if GPS disconnected
// if (!SettingsManager::instance()->menu_isSimulatorOn()) {
// // Real mode fallback protection (GPS disconnected scenario)
// if (nowHz > 50) nowHz = 50;
// if (nowHz < 3) nowHz = 3;
// }
// Simulation mode: No limits, show true CPU performance
double mc_actualSteerAngleDegrees = ModuleComm::instance()->actualSteerAngleDegrees();
//simple comp filter
gpsHz = 0.98 * gpsHz + 0.02 * nowHz;
//Initialization counter
startCounter++;
if (!isGPSPositionInitialized)
{
InitializeFirstFewGPSPositions();
//lock.unlock();
return;
}
//qDebug(qpos) << "Easting " << pn.fix.easting << "Northing" << pn.fix.northing << "Time " << swFrame.elapsed() << nowHz;
swFrame.restart();
pn.speed = pn.vtgSpeed;
CVehicle::instance()->AverageTheSpeed(pn.speed);
/*
//GPS is valid, let's bootstrap the demo field if needed
if(bootstrap_field)
{
fileCreateField();
fileSaveABLines();
bootstrap_field = false;
}
*/
//#region Heading
//calculate current heading only when moving, otherwise use last
if (headingFromSource == "Fix")
{
//#region Start
distanceCurrentStepFixDisplay = glm::Distance(prevDistFix, pn.fix);
double newDistance = Backend::instance()->m_currentField.distanceUser + distanceCurrentStepFixDisplay;
if (newDistance > 999) newDistance = 0;
Backend::instance()->currentField_setDistanceUser(newDistance);
distanceCurrentStepFixDisplay *= 100;
prevDistFix = pn.fix;
if (fabs(CVehicle::instance()->avgSpeed()) < 1.5 && !CVehicle::instance()->vehicleProperties()->firstHeadingSet())
goto byPass;
if (!CVehicle::instance()->vehicleProperties()->firstHeadingSet()) //set in steer settings, Stanley
{
prevFix.easting = stepFixPts[0].easting; prevFix.northing = stepFixPts[0].northing;
if (stepFixPts[2].isSet == 0)
{
//this is the first position no roll or offset correction
if (stepFixPts[0].isSet == 0)
{
stepFixPts[0].easting = pn.fix.easting;
stepFixPts[0].northing = pn.fix.northing;
stepFixPts[0].isSet = 1;
//lock.unlock();
return;
}
//and the second
if (stepFixPts[1].isSet == 0)
{
for (int i = totalFixSteps - 1; i > 0; i--) stepFixPts[i] = stepFixPts[i - 1];
stepFixPts[0].easting = pn.fix.easting;
stepFixPts[0].northing = pn.fix.northing;
stepFixPts[0].isSet = 1;
//lock.unlock();
return;
}
//the critcal moment for checking initial direction/heading.
for (int i = totalFixSteps - 1; i > 0; i--) stepFixPts[i] = stepFixPts[i - 1];
stepFixPts[0].easting = pn.fix.easting;
stepFixPts[0].northing = pn.fix.northing;
stepFixPts[0].isSet = 1;
Backend::instance()->m_fixFrame.gpsHeading = atan2(pn.fix.easting - stepFixPts[2].easting,
pn.fix.northing - stepFixPts[2].northing);
if (Backend::instance()->m_fixFrame.gpsHeading < 0) Backend::instance()->m_fixFrame.gpsHeading = Backend::instance()->m_fixFrame.gpsHeading + glm::twoPI;
else if (Backend::instance()->m_fixFrame.gpsHeading > glm::twoPI) Backend::instance()->m_fixFrame.gpsHeading = Backend::instance()->m_fixFrame.gpsHeading - glm::twoPI;
CVehicle::instance()->set_fixHeading ( Backend::instance()->m_fixFrame.gpsHeading );
//set the imu to gps heading offset
if (ahrs.imuHeading != 99999)
{
double imuHeading = (glm::toRadians(ahrs.imuHeading));
imuGPS_Offset = 0;
//Difference between the IMU heading and the GPS heading
double gyroDelta = (imuHeading + imuGPS_Offset) - Backend::instance()->m_fixFrame.gpsHeading;
if (gyroDelta < 0) gyroDelta += glm::twoPI;
else if (gyroDelta > glm::twoPI) gyroDelta -= glm::twoPI;
//calculate delta based on circular data problem 0 to 360 to 0, clamp to +- 2 Pi
if (gyroDelta >= -glm::PIBy2 && gyroDelta <= glm::PIBy2) gyroDelta *= -1.0;
else
{
if (gyroDelta > glm::PIBy2) { gyroDelta = glm::twoPI - gyroDelta; }
else { gyroDelta = (glm::twoPI + gyroDelta) * -1.0; }
}
if (gyroDelta > glm::twoPI) gyroDelta -= glm::twoPI;
else if (gyroDelta < -glm::twoPI) gyroDelta += glm::twoPI;
//moe the offset to line up imu with gps
imuGPS_Offset = (gyroDelta);
//rounding a floating point number doesn't make sense.
//imuGPS_Offset = Math.Round(imuGPS_Offset, 6);
if (imuGPS_Offset >= glm::twoPI) imuGPS_Offset -= glm::twoPI;
else if (imuGPS_Offset <= 0) imuGPS_Offset += glm::twoPI;
//determine the Corrected heading based on gyro and GPS
_imuCorrected = imuHeading + imuGPS_Offset;
if (_imuCorrected > glm::twoPI) _imuCorrected -= glm::twoPI;
else if (_imuCorrected < 0) _imuCorrected += glm::twoPI;
// Phase 6.0.24 Problem 18: Validate _imuCorrected before assigning to fixHeading
if (std::isfinite(_imuCorrected) && fabs(_imuCorrected) < 100.0) {
CVehicle::instance()->set_fixHeading ( _imuCorrected );
} else {
qWarning() << "Invalid _imuCorrected value:" << _imuCorrected << "- not assigned to fixHeading";
}
}
//set the camera
camera.set_camHeading(glm::toDegrees(Backend::instance()->m_fixFrame.gpsHeading));
//now we have a heading, fix the first 3
if (CVehicle::instance()->antennaOffset != 0)
{
for (int i = 0; i < 3; i++)
{
stepFixPts[i].easting = (cos(-Backend::instance()->m_fixFrame.gpsHeading) * CVehicle::instance()->antennaOffset) + stepFixPts[i].easting;
stepFixPts[i].northing = (sin(-Backend::instance()->m_fixFrame.gpsHeading) * CVehicle::instance()->antennaOffset) + stepFixPts[i].northing;
}
}
if (ahrs.imuRoll != 88888)
{
// PHASE 6.0.31: Fixed tan() → sin() for geometric correctness
// Roll correction is horizontal displacement = height × sin(roll), NOT tan(roll)
// tan() causes exponential error for large angles (15.5% error at 30°)
rollCorrectionDistance = sin(glm::toRadians((ahrs.imuRoll))) * -CVehicle::instance()->antennaHeight;
// roll to left is positive **** important!!
// not any more - April 30, 2019 - roll to right is positive Now! Still Important
for (int i = 0; i < 3; i++)
{
stepFixPts[i].easting = (cos(-Backend::instance()->m_fixFrame.gpsHeading) * rollCorrectionDistance) + stepFixPts[i].easting;
stepFixPts[i].northing = (sin(-Backend::instance()->m_fixFrame.gpsHeading) * rollCorrectionDistance) + stepFixPts[i].northing;
}
}
//get the distance from first to 2nd point, update fix with new offset/roll
stepFixPts[0].distance = glm::Distance(stepFixPts[1], stepFixPts[0]);
pn.fix.easting = stepFixPts[0].easting;
pn.fix.northing = stepFixPts[0].northing;
CVehicle::instance()->vehicleProperties()->set_firstHeadingSet(true);
TimedMessageBox(2000, "Direction Reset", "Forward is Set");
lastGPS = pn.fix;
//lock.unlock();
return;
}
}
//#endregion
//#region Offset Roll
// PHASE 6.0.33 FIX: Copy RAW GPS position from member FIRST (prevents cascade corrections)
// m_rawGpsPosition set by onNmeaDataReady() at 8 Hz (never modified by corrections)
// UpdateFixPosition() called at 50 Hz → always starts from same raw position
{
QMutexLocker lock(&m_rawGpsPositionMutex);
rawGpsPosition = m_rawGpsPosition;
}
// PHASE 6.0.33 FIX: RESET pn.fix to RAW position BEFORE applying corrections
// This ensures corrections are applied to FRESH base position, not accumulated
pn.fix.easting = rawGpsPosition.easting;
pn.fix.northing = rawGpsPosition.northing;
// Apply antenna offset correction
if (CVehicle::instance()->antennaOffset != 0)
{
pn.fix.easting = (cos(-Backend::instance()->m_fixFrame.gpsHeading) * CVehicle::instance()->antennaOffset) + pn.fix.easting;
pn.fix.northing = (sin(-Backend::instance()->m_fixFrame.gpsHeading) * CVehicle::instance()->antennaOffset) + pn.fix.northing;
}
uncorrectedEastingGraph = pn.fix.easting;
// Apply roll correction
if (ahrs.imuRoll != 88888)
{
//change for roll to the right is positive times -1
rollCorrectionDistance = sin(glm::toRadians((ahrs.imuRoll))) * -CVehicle::instance()->antennaHeight;
correctionDistanceGraph = rollCorrectionDistance;
pn.fix.easting = (cos(-Backend::instance()->m_fixFrame.gpsHeading) * rollCorrectionDistance) + pn.fix.easting;
pn.fix.northing = (sin(-Backend::instance()->m_fixFrame.gpsHeading) * rollCorrectionDistance) + pn.fix.northing;
}
//#endregion
//#region Fix Heading
double minFixHeadingDistSquared;
double newGPSHeading;
double imuHeading;
double camDelta;
double gyroDelta;
//imu on board
if (ahrs.imuHeading != 99999)
{
//check for out-of bounds fusion weights in case config
//file was edited and changed inappropriately.
//TODO move this sort of thing to FormGPS::load_settings
if (ahrs.fusionWeight > 0.4) ahrs.fusionWeight = 0.4;
if (ahrs.fusionWeight < 0.2) ahrs.fusionWeight = 0.2;
// PHASE 6.0.35: Always calculate IMU heading (even during GPS bypass)
// This ensures fixHeading is updated continuously via IMU, preventing wheel shake
imuHeading = (glm::toRadians(ahrs.imuHeading));
//how far since last fix
distanceCurrentStepFix = glm::Distance(stepFixPts[0], pn.fix);
// PHASE 6.0.35: Recalculate GPS heading ONLY if distance sufficient
// C# original: GPS heading update is conditional, but IMU fusion ALWAYS runs
if (distanceCurrentStepFix >= gpsMinimumStepDistance)
{
//userDistance can be reset
minFixHeadingDistSquared = minHeadingStepDist * minHeadingStepDist;
fixToFixHeadingDistance = 0;
for (int i = 0; i < totalFixSteps; i++)
{
fixToFixHeadingDistance = glm::DistanceSquared(stepFixPts[i], pn.fix);
currentStepFix = i;
if (fixToFixHeadingDistance > minFixHeadingDistSquared)
{
break;
}
}
if (fixToFixHeadingDistance >= (minFixHeadingDistSquared * 0.5))
{
newGPSHeading = atan2(pn.fix.easting - stepFixPts[currentStepFix].easting,
pn.fix.northing - stepFixPts[currentStepFix].northing);
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
if (ahrs.isReverseOn)
{
////what is angle between the last valid heading before stopping and one just now
delta = fabs(M_PI - fabs(fabs(newGPSHeading - _imuCorrected) - M_PI));
//ie change in direction
if (delta > 1.57) //
{
CVehicle::instance()->setIsReverse(true);
newGPSHeading += M_PI;
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
else if (newGPSHeading >= glm::twoPI) newGPSHeading -= glm::twoPI;
Backend::instance()->set_isReverseWithIMU(true);
}
else
{
CVehicle::instance()->setIsReverse(false);
Backend::instance()->set_isReverseWithIMU(false);
}
}
else
{
CVehicle::instance()->setIsReverse(false);
}
// PHASE 6.0.35: Wheel angle compensation (forwardComp/reverseComp already implemented)
if (CVehicle::instance()->isReverse())
newGPSHeading -= glm::toRadians(CVehicle::instance()->antennaPivot / 1
* mc_actualSteerAngleDegrees * ahrs.reverseComp);
else
newGPSHeading -= glm::toRadians(CVehicle::instance()->antennaPivot / 1
* mc_actualSteerAngleDegrees * ahrs.forwardComp);
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
else if (newGPSHeading >= glm::twoPI) newGPSHeading -= glm::twoPI;
Backend::instance()->m_fixFrame.gpsHeading = newGPSHeading;
// PHASE 6.0.35 FIX: Update stepFixPts ONLY when GPS heading recalculated
// This ensures stepFixPts[0] and pn.fix remain spaced apart (critical for low speed)
// C# original: stepFixPts updated BEFORE byPass label, not after
for (int i = totalFixSteps - 1; i > 0; i--) stepFixPts[i] = stepFixPts[i - 1];
stepFixPts[0].easting = rawGpsPosition.easting;
stepFixPts[0].northing = rawGpsPosition.northing;
stepFixPts[0].isSet = 1;
//#region IMU Fusion - Update GPS->IMU offset
// IMU Fusion with heading correction, add the correction
//Difference between the IMU heading and the GPS heading
gyroDelta = 0;
//if (!Backend::instance()->isReverseWithIMU)
gyroDelta = (imuHeading + imuGPS_Offset) - Backend::instance()->m_fixFrame.gpsHeading;
//else
//{
// gyroDelta = 0;
//}
if (gyroDelta < 0) gyroDelta += glm::twoPI;
else if (gyroDelta > glm::twoPI) gyroDelta -= glm::twoPI;
//calculate delta based on circular data problem 0 to 360 to 0, clamp to +- 2 Pi
if (gyroDelta >= -glm::PIBy2 && gyroDelta <= glm::PIBy2) gyroDelta *= -1.0;
else
{
if (gyroDelta > glm::PIBy2) { gyroDelta = glm::twoPI - gyroDelta; }
else { gyroDelta = (glm::twoPI + gyroDelta) * -1.0; }
}
if (gyroDelta > glm::twoPI) gyroDelta -= glm::twoPI;
else if (gyroDelta < -glm::twoPI) gyroDelta += glm::twoPI;
//move the offset to line up imu with gps
if(!Backend::instance()->isReverseWithIMU())
imuGPS_Offset += (gyroDelta * (ahrs.fusionWeight));
else
imuGPS_Offset += (gyroDelta * (0.02));
if (imuGPS_Offset > glm::twoPI) imuGPS_Offset -= glm::twoPI;
else if (imuGPS_Offset < 0) imuGPS_Offset += glm::twoPI;
//#endregion
}
// ELSE: fixToFixHeadingDistance too small -> keep existing gpsHeading and imuGPS_Offset
}
// ELSE: distanceCurrentStepFix too small -> keep existing gpsHeading and imuGPS_Offset
// PHASE 6.0.35: ALWAYS calculate imuCorrected and update fixHeading (even during GPS bypass)
// This is THE FIX: fixHeading updated at IMU rate (10 Hz) even when GPS heading stale
// Result: No wheel shake at startup, no rotation jump when movement begins
//determine the Corrected heading based on gyro and GPS
_imuCorrected = imuHeading + imuGPS_Offset;
if (_imuCorrected > glm::twoPI) _imuCorrected -= glm::twoPI;
else if (_imuCorrected < 0) _imuCorrected += glm::twoPI;
//use imu as heading when going slow
// Phase 6.0.24 Problem 18: Validate _imuCorrected before assigning to fixHeading
if (std::isfinite(_imuCorrected) && fabs(_imuCorrected) < 100.0) {
CVehicle::instance()->set_fixHeading ( _imuCorrected );
} else {
qWarning() << "Invalid _imuCorrected value:" << _imuCorrected << "- not assigned to fixHeading";
}
//#endregion
}
else
{
//how far since last fix
distanceCurrentStepFix = glm::Distance(stepFixPts[0], pn.fix);
// PHASE 6.0.35: Recalculate GPS heading ONLY if distance sufficient
// No IMU available, so fixHeading = gpsHeading (updated only when GPS moves enough)
if (distanceCurrentStepFix >= gpsMinimumStepDistance)
{
minFixHeadingDistSquared = minHeadingStepDist * minHeadingStepDist;
fixToFixHeadingDistance = 0;
for (int i = 0; i < totalFixSteps; i++)
{
// PHASE 6.0.32: Use RAW position for distance check (consistent with heading calc)
fixToFixHeadingDistance = glm::DistanceSquared(stepFixPts[i], rawGpsPosition);
currentStepFix = i;
if (fixToFixHeadingDistance > minFixHeadingDistSquared)
{
break;
}
}
if (fixToFixHeadingDistance >= minFixHeadingDistSquared * 0.5)
{
// PHASE 6.0.32: Calculate heading from RAW GPS positions (not corrected)
// Old code used pn.fix which contains CORRECTED position → heading affected by roll
newGPSHeading = atan2(rawGpsPosition.easting - stepFixPts[currentStepFix].easting,
rawGpsPosition.northing - stepFixPts[currentStepFix].northing);
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
if (ahrs.isReverseOn)
{
////what is angle between the last valid heading before stopping and one just now
delta = fabs(M_PI - fabs(fabs(newGPSHeading - Backend::instance()->m_fixFrame.gpsHeading) - M_PI));
filteredDelta = delta * 0.2 + filteredDelta * 0.8;
//filtered delta different then delta
if (fabs(filteredDelta - delta) > 0.5)
{
CVehicle::instance()->setIsChangingDirection(true);
}
else
{
CVehicle::instance()->setIsChangingDirection(false);
}
//we can't be sure if changing direction so do nothing
if (CVehicle::instance()->isChangingDirection())
{
// Skip heading update when changing direction (unstable)
}
else
{
//ie change in direction
if (filteredDelta > 1.57) //
{
CVehicle::instance()->setIsReverse(true);
newGPSHeading += M_PI;
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
else if (newGPSHeading >= glm::twoPI) newGPSHeading -= glm::twoPI;
}
else
CVehicle::instance()->setIsReverse(false);
// PHASE 6.0.35: Wheel angle compensation (forwardComp/reverseComp already implemented)
if (CVehicle::instance()->isReverse())
newGPSHeading -= glm::toRadians(CVehicle::instance()->antennaPivot / 1
* mc_actualSteerAngleDegrees * ahrs.reverseComp);
else
newGPSHeading -= glm::toRadians(CVehicle::instance()->antennaPivot / 1
* mc_actualSteerAngleDegrees * ahrs.forwardComp);
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
else if (newGPSHeading >= glm::twoPI) newGPSHeading -= glm::twoPI;
//set the headings
Backend::instance()->m_fixFrame.gpsHeading = newGPSHeading;
CVehicle::instance()->set_fixHeading ( Backend::instance()->m_fixFrame.gpsHeading );
// PHASE 6.0.35 FIX: Update stepFixPts when heading recalculated (No IMU reverse path)
for (int i = totalFixSteps - 1; i > 0; i--) stepFixPts[i] = stepFixPts[i - 1];
stepFixPts[0].easting = rawGpsPosition.easting;
stepFixPts[0].northing = rawGpsPosition.northing;
stepFixPts[0].isSet = 1;
}
}
else
{
CVehicle::instance()->setIsReverse(false);
// PHASE 6.0.35 FIX: Apply wheel angle compensation in forward mode too!
// Bug: compensation was only applied in reverse detection branch
newGPSHeading -= glm::toRadians(CVehicle::instance()->antennaPivot / 1
* mc_actualSteerAngleDegrees * ahrs.forwardComp);
if (newGPSHeading < 0) newGPSHeading += glm::twoPI;
else if (newGPSHeading >= glm::twoPI) newGPSHeading -= glm::twoPI;
//set the headings
Backend::instance()->m_fixFrame.gpsHeading = newGPSHeading;
CVehicle::instance()->set_fixHeading ( Backend::instance()->m_fixFrame.gpsHeading );
// PHASE 6.0.35 FIX: Update stepFixPts when heading recalculated (No IMU forward path)
for (int i = totalFixSteps - 1; i > 0; i--) stepFixPts[i] = stepFixPts[i - 1];
stepFixPts[0].easting = rawGpsPosition.easting;
stepFixPts[0].northing = rawGpsPosition.northing;
stepFixPts[0].isSet = 1;
}
}
// ELSE: fixToFixHeadingDistance too small -> keep existing gpsHeading and fixHeading
}
// ELSE: distanceCurrentStepFix too small -> keep existing gpsHeading and fixHeading
}
// PHASE 6.0.35 FIX: stepFixPts update moved BEFORE afterByPass label (see lines 355-361, 505-509, 523-527)
// This ensures stepFixPts[0] only updated when heading recalculated → fixes low-speed heading update bug
//#endregion
//#region Camera
camDelta = CVehicle::instance()->fixHeading() - smoothCamHeading;
if (camDelta < 0) camDelta += glm::twoPI;
else if (camDelta > glm::twoPI) camDelta -= glm::twoPI;
//calculate delta based on circular data problem 0 to 360 to 0, clamp to +- 2 Pi
if (camDelta >= -glm::PIBy2 && camDelta <= glm::PIBy2) camDelta *= -1.0;
else
{
if (camDelta > glm::PIBy2) { camDelta = glm::twoPI - camDelta; }
else { camDelta = (glm::twoPI + camDelta) * -1.0; }
}
if (camDelta > glm::twoPI) camDelta -= glm::twoPI;
else if (camDelta < -glm::twoPI) camDelta += glm::twoPI;
smoothCamHeading -= camDelta * Camera::camSmoothFactor();
if (smoothCamHeading > glm::twoPI) smoothCamHeading -= glm::twoPI;
else if (smoothCamHeading < -glm::twoPI) smoothCamHeading += glm::twoPI;
camera.set_camHeading(glm::toDegrees(smoothCamHeading));
// PHASE 6.0.35 FIX: Skip byPass in normal flow (heading with wheel compensation already calculated)
// byPass should only execute when jumped to from line 98 (slow speed / no initial heading)
// Without this goto, byPass overwrites fixHeading (with wheel comp) → causes crab motion!
goto afterByPass;
//#endregion
//Calculate a million other things
byPass:
if (ahrs.imuHeading != 99999)
{
_imuCorrected = (glm::toRadians(ahrs.imuHeading)) + imuGPS_Offset;
if (_imuCorrected > glm::twoPI) _imuCorrected -= glm::twoPI;
else if (_imuCorrected < 0) _imuCorrected += glm::twoPI;
//use imu as heading when going slow
// Phase 6.0.24 Problem 18: Validate _imuCorrected before assigning to fixHeading
if (std::isfinite(_imuCorrected) && fabs(_imuCorrected) < 100.0) {
CVehicle::instance()->set_fixHeading ( _imuCorrected );
} else {
qWarning() << "Invalid _imuCorrected value:" << _imuCorrected << "- not assigned to fixHeading";
}
}
camDelta = CVehicle::instance()->fixHeading() - smoothCamHeading;
if (camDelta < 0) camDelta += glm::twoPI;
else if (camDelta > glm::twoPI) camDelta -= glm::twoPI;
//calculate delta based on circular data problem 0 to 360 to 0, clamp to +- 2 Pi
if (camDelta >= -glm::PIBy2 && camDelta <= glm::PIBy2) camDelta *= -1.0;
else
{
if (camDelta > glm::PIBy2) { camDelta = glm::twoPI - camDelta; }
else { camDelta = (glm::twoPI + camDelta) * -1.0; }
}
if (camDelta > glm::twoPI) camDelta -= glm::twoPI;
else if (camDelta < -glm::twoPI) camDelta += glm::twoPI;
smoothCamHeading -= camDelta * Camera::camSmoothFactor();
if (smoothCamHeading > glm::twoPI) smoothCamHeading -= glm::twoPI;
else if (smoothCamHeading < -glm::twoPI) smoothCamHeading += glm::twoPI;
camera.set_camHeading(glm::toDegrees(smoothCamHeading));
afterByPass:
TheRest();
} else if (headingFromSource == "VTG")
{
CVehicle::instance()->vehicleProperties()->set_firstHeadingSet(true);
if (CVehicle::instance()->avgSpeed() > 1)
{
//use NMEA headings for camera and tractor graphic
CVehicle::instance()->set_fixHeading ( glm::toRadians(pn.headingTrue) );
camera.set_camHeading(pn.headingTrue);
Backend::instance()->m_fixFrame.gpsHeading = CVehicle::instance()->fixHeading();
}
//grab the most current fix to last fix distance
distanceCurrentStepFix = glm::Distance(pn.fix, prevFix);
//#region Antenna Offset
if (CVehicle::instance()->antennaOffset != 0)
{
pn.fix.easting = (cos(-CVehicle::instance()->fixHeading()) * CVehicle::instance()->antennaOffset) + pn.fix.easting;
pn.fix.northing = (sin(-CVehicle::instance()->fixHeading()) * CVehicle::instance()->antennaOffset) + pn.fix.northing;
}
//#endregion
uncorrectedEastingGraph = pn.fix.easting;
//an IMU with heading correction, add the correction
if (ahrs.imuHeading != 99999)
{
//current gyro angle in radians
double correctionHeading = (glm::toRadians(ahrs.imuHeading));
//Difference between the IMU heading and the GPS heading
double gyroDelta = (correctionHeading + imuGPS_Offset) - Backend::instance()->m_fixFrame.gpsHeading;
if (gyroDelta < 0) gyroDelta += glm::twoPI;
//calculate delta based on circular data problem 0 to 360 to 0, clamp to +- 2 Pi
if (gyroDelta >= -glm::PIBy2 && gyroDelta <= glm::PIBy2) gyroDelta *= -1.0;
else
{
if (gyroDelta > glm::PIBy2) { gyroDelta = glm::twoPI - gyroDelta; }
else { gyroDelta = (glm::twoPI + gyroDelta) * -1.0; }
}
if (gyroDelta > glm::twoPI) gyroDelta -= glm::twoPI;
if (gyroDelta < -glm::twoPI) gyroDelta += glm::twoPI;
//if the gyro and last corrected fix is < 10 degrees, super low pass for gps
if (fabs(gyroDelta) < 0.18)
{
//a bit of delta and add to correction to current gyro
imuGPS_Offset += (gyroDelta * (0.1));
if (imuGPS_Offset > glm::twoPI) imuGPS_Offset -= glm::twoPI;
if (imuGPS_Offset < -glm::twoPI) imuGPS_Offset += glm::twoPI;
}
else
{
//a bit of delta and add to correction to current gyro
imuGPS_Offset += (gyroDelta * (0.2));
if (imuGPS_Offset > glm::twoPI) imuGPS_Offset -= glm::twoPI;
if (imuGPS_Offset < -glm::twoPI) imuGPS_Offset += glm::twoPI;
}
//determine the Corrected heading based on gyro and GPS
_imuCorrected = correctionHeading + imuGPS_Offset;
if (_imuCorrected > glm::twoPI) _imuCorrected -= glm::twoPI;
if (_imuCorrected < 0) _imuCorrected += glm::twoPI;
// Phase 6.0.24 Problem 18: Validate _imuCorrected before assigning to fixHeading
if (std::isfinite(_imuCorrected) && fabs(_imuCorrected) < 100.0) {
CVehicle::instance()->set_fixHeading ( _imuCorrected);
} else {
qWarning() << "Invalid _imuCorrected value:" << _imuCorrected << "- not assigned to fixHeading";
}
double new_camHeading = CVehicle::instance()->fixHeading();
if (new_camHeading > glm::twoPI) new_camHeading -= glm::twoPI;
camera.set_camHeading(glm::toDegrees(new_camHeading));
}
//#region Roll
if (ahrs.imuRoll != 88888)
{
//change for roll to the right is positive times -1
rollCorrectionDistance = sin(glm::toRadians((ahrs.imuRoll))) * -CVehicle::instance()->antennaHeight;
correctionDistanceGraph = rollCorrectionDistance;
// roll to left is positive **** important!!
// not any more - April 30, 2019 - roll to right is positive Now! Still Important
pn.fix.easting = (cos(-CVehicle::instance()->fixHeading()) * rollCorrectionDistance) + pn.fix.easting;
pn.fix.northing = (sin(-CVehicle::instance()->fixHeading()) * rollCorrectionDistance) + pn.fix.northing;
}
//#endregion Roll
TheRest();
//most recent fixes are now the prev ones
prevFix.easting = pn.fix.easting; prevFix.northing = pn.fix.northing;
} else if (headingFromSource == "Dual")
{
CVehicle::instance()->vehicleProperties()->set_firstHeadingSet(true);
//use Dual Antenna heading for camera and tractor graphic
CVehicle::instance()->set_fixHeading ( glm::toRadians(pn.headingTrueDual) );
Backend::instance()->m_fixFrame.gpsHeading = CVehicle::instance()->fixHeading();
uncorrectedEastingGraph = pn.fix.easting;
if (CVehicle::instance()->antennaOffset != 0)
{
pn.fix.easting = (cos(-CVehicle::instance()->fixHeading()) * CVehicle::instance()->antennaOffset) + pn.fix.easting;
pn.fix.northing = (sin(-CVehicle::instance()->fixHeading()) * CVehicle::instance()->antennaOffset) + pn.fix.northing;
}
if (ahrs.imuRoll != 88888 && CVehicle::instance()->antennaHeight != 0)
{
//change for roll to the right is positive times -1
rollCorrectionDistance = sin(glm::toRadians((ahrs.imuRoll))) * -CVehicle::instance()->antennaHeight;
correctionDistanceGraph = rollCorrectionDistance;
// PHASE 6.0.35 FIX: Use fixHeading (not gpsHeading) for geometric consistency
pn.fix.easting = (cos(-CVehicle::instance()->fixHeading()) * rollCorrectionDistance) + pn.fix.easting;
pn.fix.northing = (sin(-CVehicle::instance()->fixHeading()) * rollCorrectionDistance) + pn.fix.northing;
}
//grab the most current fix and save the distance from the last fix
distanceCurrentStepFix = glm::Distance(pn.fix, prevDistFix);
//userDistance can be reset
double userDistance = Backend::instance()->m_currentField.distanceUser + distanceCurrentStepFix;
if (userDistance > 999) userDistance = 0;
Backend::instance()->currentField_setDistanceUser(userDistance);
distanceCurrentStepFixDisplay = distanceCurrentStepFix * 100;
prevDistFix = pn.fix;
if (glm::DistanceSquared(lastReverseFix, pn.fix) > 0.20)
{
//most recent heading
double newHeading = atan2(pn.fix.easting - lastReverseFix.easting,
pn.fix.northing - lastReverseFix.northing);
if (newHeading < 0) newHeading += glm::twoPI;
//what is angle between the last reverse heading and current dual heading
double delta = fabs(M_PI - fabs(fabs(newHeading - CVehicle::instance()->fixHeading()) - M_PI));
//are we going backwards
CVehicle::instance()->setIsReverse(delta > 2 ? true : false);
//save for next meter check
lastReverseFix = pn.fix;
}
double camDelta = CVehicle::instance()->fixHeading() - smoothCamHeading;
if (camDelta < 0) camDelta += glm::twoPI;
else if (camDelta > glm::twoPI) camDelta -= glm::twoPI;
//calculate delta based on circular data problem 0 to 360 to 0, clamp to +- 2 Pi
if (camDelta >= -glm::PIBy2 && camDelta <= glm::PIBy2) camDelta *= -1.0;
else
{
if (camDelta > glm::PIBy2) { camDelta = glm::twoPI - camDelta; }
else { camDelta = (glm::twoPI + camDelta) * -1.0; }
}
if (camDelta > glm::twoPI) camDelta -= glm::twoPI;
else if (camDelta < -glm::twoPI) camDelta += glm::twoPI;
smoothCamHeading -= camDelta * Camera::camSmoothFactor();
if (smoothCamHeading > glm::twoPI) smoothCamHeading -= glm::twoPI;
else if (smoothCamHeading < -glm::twoPI) smoothCamHeading += glm::twoPI;
camera.set_camHeading(glm::toDegrees(smoothCamHeading));
TheRest();
}
//else {
//}
if (CVehicle::instance()->fixHeading() >= glm::twoPI)
CVehicle::instance()->set_fixHeading( CVehicle::instance()->fixHeading() - glm::twoPI );
//#endregion
//
//#region Corrected Position for GPS_OUT
//NOTE: Michael, I'm not sure about this entire region
double rollCorrectedLat;
double rollCorrectedLon;
// Phase 6.3.1: Use PropertyWrapper for safe QObject access
pn.ConvertLocalToWGS84(pn.fix.northing, pn.fix.easting, rollCorrectedLat, rollCorrectedLon);
QByteArray pgnRollCorrectedLatLon(22, 0);
pgnRollCorrectedLatLon[0] = 0x80;
pgnRollCorrectedLatLon[1] = 0x81;
pgnRollCorrectedLatLon[2] = 0x7F;
pgnRollCorrectedLatLon[3] = 0x64;
pgnRollCorrectedLatLon[4] = 16;
std::memcpy(pgnRollCorrectedLatLon.data() + 5, &rollCorrectedLon, 8);
std::memcpy(pgnRollCorrectedLatLon.data() + 13, &rollCorrectedLat, 8);
// SendPgnToLoop(pgnRollCorrectedLatLon); // ❌ REMOVED - Phase 4.6: AgIOService Workers handle PGN
// GPS position data now flows through: AgIOService → FormGPS → pn/vehicle → OpenGL
//#endregion
//#region AutoSteer
//preset the values
CVehicle::instance()->set_guidanceLineDistanceOff (32000);
if (MainWindowState::instance()->isContourBtnOn())
{
ct.DistanceFromContourLine(MainWindowState::instance()->isBtnAutoSteerOn(), *CVehicle::instance(), yt, ahrs, pn, CVehicle::instance()->pivotAxlePos, CVehicle::instance()->steerAxlePos);
}
else
{
//auto track routine
// PHASE 6.0.42.9: Fix auto-track condition (C# Position.designer.cs:826)
// Added timer check to prevent rapid switching (max 1 switch/second)
if (track.isAutoTrack() && !MainWindowState::instance()->isBtnAutoSteerOn() && track.autoTrack3SecTimer >= 1)
{
track.autoTrack3SecTimer = 0; // Reset timer after switch
track.SwitchToClosestRefTrack(CVehicle::instance()->steerAxlePos, *CVehicle::instance());
}
bool autoSteerState = MainWindowState::instance()->isBtnAutoSteerOn();
track.BuildCurrentLine(CVehicle::instance()->pivotAxlePos,secondsSinceStart,autoSteerState,yt,*CVehicle::instance(),bnd,ahrs,pn);
}
// autosteer at full speed of updates
//if the whole path driving driving process is green
if (RecordedPath::instance()->isDrivingRecordedPath()) RecordedPath::instance()->UpdatePosition(yt, MainWindowState::instance()->isBtnAutoSteerOn());
// If Drive button off - normal autosteer
if (!CVehicle::instance()->isInFreeDriveMode())
{
//fill up0 the appropriate arrays with new values
p_254.pgn[CPGN_FE::speedHi] = (char)((int)(fabs(CVehicle::instance()->avgSpeed()) * 10.0) >> 8);
p_254.pgn[CPGN_FE::speedLo] = (char)((int)(fabs(CVehicle::instance()->avgSpeed()) * 10.0));
//mc.machineControlData[mc.cnSpeed] = mc.autoSteerData[mc.sdSpeed];
//save distance for display
lightbarDistance = CVehicle::instance()->guidanceLineDistanceOff();
if (!MainWindowState::instance()->isBtnAutoSteerOn()) //32020 means auto steer is off
{
//NOTE: Is this supposed to be commented out?
//CVehicle::instance()->set_guidanceLineDistanceOff (32020);
p_254.pgn[CPGN_FE::status] = 0; // PHASE 6.0.29: OFF → send 0 (match C# original)
}
else p_254.pgn[CPGN_FE::status] = 1; // PHASE 6.0.29: ON → send 1 (match C# original)
if (RecordedPath::instance()->isDrivingRecordedPath() || RecordedPath::instance()->isFollowingDubinsToPath) p_254.pgn[CPGN_FE::status] = 1; // PHASE 6.0.29: Force ON (match C# original)
// PHASE 6.0.42.8: Auto-snap track to pivot when autosteer turns ON
// C# original: OpenGL.Designer.cs:1858-1876
// Behavior: When autosteer activates, automatically center track to current tractor position
// This is a ONE-TIME snap (not continuous tracking) controlled by isAutoSnapped flag
if (ModuleComm::instance()->steerSwitchHigh())
{
// Manual steer override active (switch on handlebar)
// Reset auto-snap flag so it can snap again when autosteer re-enabled
track.setIsAutoSnapped(false);
}
else if (MainWindowState::instance()->isBtnAutoSteerOn())
{
// Autosteer is ON → perform auto-snap if enabled and not already snapped
if (track.isAutoSnapToPivot() && !track.isAutoSnapped())
{
track.SnapToPivot(); // Nudge track to align with current pivot position
track.setIsAutoSnapped(true); // Mark as snapped (prevents re-snap until reset)
}
}
else
{
// Autosteer is OFF → reset auto-snap flag for next activation cycle
track.setIsAutoSnapped(false);
}
//mc.autoSteerData[7] = unchecked((byte)(CVehicle::instance()->guidanceLineDistanceOff() >> 8));
//mc.autoSteerData[8] = unchecked((byte)(CVehicle::instance()->guidanceLineDistanceOff()));
//convert to cm from mm and divide by 2 - lightbar
int distanceX2;
//if (CVehicle::instance()->set_guidanceLineDistanceOff() == 32020 || CVehicle::instance()->guidanceLineDistanceOff() == 32000)
if (!MainWindowState::instance()->isBtnAutoSteerOn() || CVehicle::instance()->guidanceLineDistanceOff() == 32000)
distanceX2 = 255;
else
{
distanceX2 = (int)(CVehicle::instance()->guidanceLineDistanceOff() * 0.05);
if (distanceX2 < -127) distanceX2 = -127;
else if (distanceX2 > 127) distanceX2 = 127;
distanceX2 += 127;
}
p_254.pgn[CPGN_FE::lineDistance] = (char)distanceX2;
if (!SimInterface::instance()->isRunning())
{
if (MainWindowState::instance()->isBtnAutoSteerOn() && CVehicle::instance()->avgSpeed() > SettingsManager::instance()->as_maxSteerSpeed())
{
MainWindowState::instance()->set_isBtnAutoSteerOn(false);
if (isMetric)
TimedMessageBox(3000, tr("AutoSteer Disabled"), tr("Above Maximum Safe Steering Speed: ") + locale.toString(CVehicle::instance()->maxSteerSpeed, 'g', 1) + tr(" Kmh"));
else
TimedMessageBox(3000, tr("AutoSteer Disabled"), tr("Above Maximum Safe Steering Speed: ") + locale.toString(CVehicle::instance()->maxSteerSpeed * 0.621371, 'g', 1) + tr(" MPH"));
}
if (MainWindowState::instance()->isBtnAutoSteerOn() && CVehicle::instance()->avgSpeed() < SettingsManager::instance()->as_minSteerSpeed())
{
minSteerSpeedTimer++;
if (minSteerSpeedTimer > 80)
{
MainWindowState::instance()->set_isBtnAutoSteerOn(false);
if (isMetric)
TimedMessageBox(3000, tr("AutoSteer Disabled"), tr("Below Minimum Safe Steering Speed: ") + locale.toString(CVehicle::instance()->minSteerSpeed, 'g', 1) + tr(" Kmh"));
else
TimedMessageBox(3000, tr("AutoSteer Disabled"), tr("Below Minimum Safe Steering Speed: ") + locale.toString(CVehicle::instance()->minSteerSpeed * 0.621371, 'g', 1) + tr(" MPH"));
}
}
else
{
minSteerSpeedTimer = 0;
}
}
double tanSteerAngle = tan(glm::toRadians(((double)(CVehicle::instance()->guidanceLineSteerAngle)) * 0.01));
double tanActSteerAngle = tan(glm::toRadians(mc_actualSteerAngleDegrees));