Rise
The Vieneo Province
Loading...
Searching...
No Matches
TelemetrySnapshot.cpp
Go to the documentation of this file.
1#include "TelemetrySnapshot.h"
2
3#include <algorithm>
4#include <cassert>
5#include <chrono>
6#include <cmath>
7#include <limits>
8
9namespace
10{
11 constexpr double Pi = 3.1415926535897932384626433832795;
12
13 double Clamp(double value, double minimum, double maximum)
14 {
15 return std::max(minimum, std::min(value, maximum));
16 }
17
18 double Dot(const Telemetry::Quaternion& a, const Telemetry::Quaternion& b)
19 {
20 return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
21 }
22
24 {
25 return {
26 a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
27 a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
28 a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
29 a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z
30 };
31 }
32
33 Telemetry::Quaternion FromYawPitchRoll(double yaw, double pitch, double roll)
34 {
35 const double halfYaw = yaw * 0.5;
36 const double halfPitch = pitch * 0.5;
37 const double halfRoll = roll * 0.5;
38 const double cy = std::cos(halfYaw);
39 const double sy = std::sin(halfYaw);
40 const double cp = std::cos(halfPitch);
41 const double sp = std::sin(halfPitch);
42 const double cr = std::cos(halfRoll);
43 const double sr = std::sin(halfRoll);
44
46 result.x = cy * sp * cr + sy * cp * sr;
47 result.y = sy * cp * cr - cy * sp * sr;
48 result.z = cy * cp * sr - sy * sp * cr;
49 result.w = cy * cp * cr + sy * sp * sr;
51 return result;
52 }
53
54 Telemetry::Vec3 HermitePosition(const Telemetry::MotionSnapshot& first,
55 const Telemetry::MotionSnapshot& second, double amount, double duration)
56 {
57 const double t2 = amount * amount;
58 const double t3 = t2 * amount;
59 const double h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
60 const double h10 = t3 - 2.0 * t2 + amount;
61 const double h01 = -2.0 * t3 + 3.0 * t2;
62 const double h11 = t3 - t2;
63 return first.position * h00 + first.positionDerivative * (h10 * duration) +
64 second.position * h01 + second.positionDerivative * (h11 * duration);
65 }
66
67 Telemetry::Vec3 HermiteVelocity(const Telemetry::MotionSnapshot& first,
68 const Telemetry::MotionSnapshot& second, double amount, double duration)
69 {
70 if (duration <= std::numeric_limits<double>::epsilon())
71 return second.velocity;
72 const double t2 = amount * amount;
73 const double dh00 = (6.0 * t2 - 6.0 * amount) / duration;
74 const double dh10 = 3.0 * t2 - 4.0 * amount + 1.0;
75 const double dh01 = (-6.0 * t2 + 6.0 * amount) / duration;
76 const double dh11 = 3.0 * t2 - 2.0 * amount;
77 return first.position * dh00 + first.positionDerivative * dh10 +
78 second.position * dh01 + second.positionDerivative * dh11;
79 }
80}
81
82namespace Telemetry
83{
84 Vec3 Vec3::operator+(const Vec3& rhs) const { return {x + rhs.x, y + rhs.y, z + rhs.z}; }
85 Vec3 Vec3::operator-(const Vec3& rhs) const { return {x - rhs.x, y - rhs.y, z - rhs.z}; }
86 Vec3 Vec3::operator*(double scalar) const { return {x * scalar, y * scalar, z * scalar}; }
87 Vec3 Vec3::operator/(double scalar) const { return scalar == 0.0 ? Vec3{} : Vec3{x / scalar, y / scalar, z / scalar}; }
89 {
90 x += rhs.x;
91 y += rhs.y;
92 z += rhs.z;
93 return *this;
94 }
95
96 bool IsFinite(const Vec3& value)
97 {
98 return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z);
99 }
100
101 bool IsFinite(const Quaternion& value)
102 {
103 return std::isfinite(value.x) && std::isfinite(value.y) &&
104 std::isfinite(value.z) && std::isfinite(value.w);
105 }
106
107 double Length(const Vec3& value)
108 {
109 return std::sqrt(value.x * value.x + value.y * value.y + value.z * value.z);
110 }
111
112 double QuaternionLength(const Quaternion& value)
113 {
114 return std::sqrt(value.x * value.x + value.y * value.y + value.z * value.z + value.w * value.w);
115 }
116
118 {
119 if (!IsFinite(value))
120 return false;
121 const double length = QuaternionLength(value);
122 if (!std::isfinite(length) || length < 0.5 || length > 2.0)
123 return false;
124 value.x /= length;
125 value.y /= length;
126 value.z /= length;
127 value.w /= length;
128 return true;
129 }
130
132 {
133 // REF_INANOTHER is zero in the shared wire contract. These are discrete
134 // cargo-bay placements derived from metadata, not continuous motion.
135 return reference != 0;
136 }
137
138 Quaternion Slerp(const Quaternion& aValue, const Quaternion& bValue, double amount)
139 {
140 Quaternion a = aValue;
141 Quaternion b = bValue;
143 return {};
144 amount = Clamp(amount, 0.0, 1.0);
145
146 double dot = Dot(a, b);
147 if (dot < 0.0)
148 {
149 dot = -dot;
150 b.x = -b.x;
151 b.y = -b.y;
152 b.z = -b.z;
153 b.w = -b.w;
154 }
155
156 Quaternion result;
157 if (dot > 0.9995)
158 {
159 result.x = a.x + amount * (b.x - a.x);
160 result.y = a.y + amount * (b.y - a.y);
161 result.z = a.z + amount * (b.z - a.z);
162 result.w = a.w + amount * (b.w - a.w);
163 NormalizeQuaternion(result);
164 return result;
165 }
166
167 const double theta = std::acos(Clamp(dot, -1.0, 1.0));
168 const double sinTheta = std::sin(theta);
169 const double firstWeight = std::sin((1.0 - amount) * theta) / sinTheta;
170 const double secondWeight = std::sin(amount * theta) / sinTheta;
171 result.x = a.x * firstWeight + b.x * secondWeight;
172 result.y = a.y * firstWeight + b.y * secondWeight;
173 result.z = a.z * firstWeight + b.z * secondWeight;
174 result.w = a.w * firstWeight + b.w * secondWeight;
175 NormalizeQuaternion(result);
176 return result;
177 }
178
179 Quaternion IntegrateAngularVelocity(const Quaternion& orientation, const Vec3& angularVelocity, double seconds)
180 {
181 if (seconds <= 0.0 || !IsFinite(angularVelocity))
182 return orientation;
183 Quaternion result = Multiply(orientation,
184 FromYawPitchRoll(angularVelocity.y * seconds, angularVelocity.x * seconds, angularVelocity.z * seconds));
185 if (!NormalizeQuaternion(result))
186 return {};
187 return result;
188 }
189
190 bool IsNewerUShort(std::uint16_t incoming, std::uint16_t previous)
191 {
192 const std::uint16_t delta = static_cast<std::uint16_t>(incoming - previous);
193 return delta >= 1 && delta <= 32767;
194 }
195
196 bool IsNewerModulo255(std::uint8_t incoming, std::uint8_t previous)
197 {
198 if (incoming >= 255 || previous >= 255)
199 return false;
200 const unsigned delta = (static_cast<unsigned>(incoming) + 255U - static_cast<unsigned>(previous)) % 255U;
201 return delta >= 1 && delta <= 127;
202 }
203
204 std::uint16_t SourceTimeDeltaMilliseconds(std::uint16_t incoming, std::uint16_t previous)
205 {
206 return static_cast<std::uint16_t>(incoming - previous);
207 }
208
209 bool HasExactPayloadLength(std::size_t actualBytes, std::size_t expectedBytes)
210 {
211 return actualBytes == expectedBytes;
212 }
213
215 {
216 static const auto epoch = std::chrono::steady_clock::now();
217 return std::chrono::duration<double>(std::chrono::steady_clock::now() - epoch).count();
218 }
219
220 Vec3 WeaponFrameEndpoint(const Vec3& presentationPosition, const Vec3& velocity,
221 double elapsedSeconds, bool hasAuthoritativePresentation)
222 {
223 if (hasAuthoritativePresentation || !std::isfinite(elapsedSeconds) || elapsedSeconds <= 0.0)
224 return presentationPosition;
225 return presentationPosition + velocity * elapsedSeconds;
226 }
227
229
230 void SnapshotChannel::Configure(SequenceMode sequenceMode, const ChannelConfig& config)
231 {
232 sequenceMode_ = sequenceMode;
233 config_ = config;
234 }
235
236 void SnapshotChannel::Reset(int identity, int reference, int parentSlot, bool requireLowBootstrapSequence)
237 {
238 const std::uint32_t generation = metrics_.generation + 1;
239 metrics_ = {};
240 metrics_.generation = generation;
241 metrics_.identity = identity;
242 metrics_.reference = reference;
243 metrics_.parentSlot = parentSlot;
244 requireLowBootstrapSequence_ = requireLowBootstrapSequence;
245 intervalInitialized_ = false;
246 hasRawReceipt_ = false;
251 ClearHistory();
252 }
253
265
277
278 void SnapshotChannel::RecordIncoming(double receiptSeconds)
279 {
280 if (packetWindowCount_ == 0)
281 {
282 packetWindowStartSeconds_ = receiptSeconds;
284 return;
285 }
287 const double elapsed = receiptSeconds - packetWindowStartSeconds_;
288 if (elapsed >= 0.5)
289 {
290 metrics_.incomingPacketsPerSecond = static_cast<double>(packetWindowCount_ - 1) / elapsed;
291 packetWindowStartSeconds_ = receiptSeconds;
293 }
294 }
295
296 void SnapshotChannel::UpdateCadence(double rawIntervalSeconds)
297 {
298 // Near-simultaneous arrivals are a catch-up burst, not a new source cadence.
299 if (!std::isfinite(rawIntervalSeconds) || rawIntervalSeconds < 0.005)
300 return;
301 const double interval = Clamp(rawIntervalSeconds, 0.005, 10.0);
303 {
307 return;
308 }
309
310 constexpr double Alpha = 0.15;
311 const double previous = metrics_.measuredIntervalSeconds;
312 metrics_.measuredIntervalSeconds = previous + Alpha * (interval - previous);
313 const double deviation = std::abs(interval - previous);
314 metrics_.jitterSeconds += Alpha * (deviation - metrics_.jitterSeconds);
315 }
316
317 void SnapshotChannel::UpdateSourceCadence(double sourceIntervalSeconds)
318 {
319 if (!std::isfinite(sourceIntervalSeconds) || sourceIntervalSeconds <= 0.0 ||
320 sourceIntervalSeconds > config_.maximumSourceDeltaSeconds)
321 return;
323 {
324 sourceIntervalSeconds_ = sourceIntervalSeconds;
326 return;
327 }
328 constexpr double Alpha = 0.15;
329 sourceIntervalSeconds_ += Alpha * (sourceIntervalSeconds - sourceIntervalSeconds_);
330 }
331
332 std::uint16_t SnapshotChannel::ForwardDelta(std::uint16_t incoming) const
333 {
335 return static_cast<std::uint16_t>(incoming - metrics_.lastAcceptedSequence);
336 return static_cast<std::uint16_t>((incoming + 255U - metrics_.lastAcceptedSequence) % 255U);
337 }
338
339 Acceptance SnapshotChannel::Push(MotionSnapshot snapshot, double receiptSeconds)
340 {
341 if (!std::isfinite(receiptSeconds) || receiptSeconds < 0.0)
342 {
344 return Acceptance::Invalid;
345 }
346 RecordIncoming(receiptSeconds);
347 if (!snapshot.hasPositionDerivative)
348 snapshot.positionDerivative = snapshot.velocity;
349 if (
350 !IsFinite(snapshot.position) || !IsFinite(snapshot.positionDerivative) || !IsFinite(snapshot.velocity) ||
351 !IsFinite(snapshot.acceleration) || !IsFinite(snapshot.angularVelocity) ||
352 !IsFinite(snapshot.thrust) || !IsFinite(snapshot.controlDeflection) ||
353 !std::isfinite(snapshot.steerDeflection) ||
354 !std::isfinite(snapshot.expectedIntervalSeconds) ||
355 !NormalizeQuaternion(snapshot.orientation) ||
356 (sequenceMode_ == SequenceMode::Modulo255 && snapshot.sequence >= 255))
357 {
359 return Acceptance::Invalid;
360 }
361
362 const bool hadSequence = metrics_.hasSequence;
363 std::uint16_t deliveryDelta = 0;
364 if (!hadSequence)
365 {
367 {
370 }
371 }
372 else
373 {
374 deliveryDelta = ForwardDelta(snapshot.sequence);
375 if (deliveryDelta == 0)
376 {
379 }
380 const std::uint16_t maximumForward = sequenceMode_ == SequenceMode::UShort ? 32767 : 127;
381 if (deliveryDelta > maximumForward)
382 {
385 }
386 metrics_.sequenceGaps += deliveryDelta - 1;
387 }
388
389 snapshot.receiptSeconds = receiptSeconds;
390 const double rawInterval = hasRawReceipt_ ? receiptSeconds - lastRawReceiptSeconds_ : 0.0;
391 if (hasRawReceipt_)
392 UpdateCadence(rawInterval);
393 lastRawReceiptSeconds_ = receiptSeconds;
394 hasRawReceipt_ = true;
395
396 metrics_.hasSequence = true;
398 metrics_.lastDeliverySequenceDelta = deliveryDelta;
400 metrics_.identity = snapshot.identity;
401 metrics_.reference = snapshot.reference;
402 metrics_.parentSlot = snapshot.parentSlot;
404
405 const bool hadSourceObservation = hasSourceObservation_;
406 const std::uint16_t sourceDeltaMs = hadSourceObservation ?
408 const std::uint16_t revisionDelta = hadSourceObservation ?
409 static_cast<std::uint16_t>(snapshot.sourceRevision - lastObservedSourceRevision_) : 0;
410 const std::uint32_t maximumSourceDeltaMs = static_cast<std::uint32_t>(
411 config_.maximumSourceDeltaSeconds * 1000.0 + 0.5);
412 const bool plausibleSourceDelta = sourceDeltaMs >= 1 && sourceDeltaMs <= maximumSourceDeltaMs;
413 const bool usesSourceRevision = sequenceMode_ == SequenceMode::UShort;
414 const bool revisionAdvanced = hadSourceObservation && IsNewerUShort(
416 const bool revisionMovedBackward = usesSourceRevision && hadSourceObservation && revisionDelta > 32767;
417 const bool legacyZeroTransition = hadSourceObservation && lastObservedSampleTimeMs_ == 0 &&
418 (!usesSourceRevision || lastObservedSourceRevision_ == 0) &&
419 (snapshot.sampleTimeMs != 0 || (usesSourceRevision && snapshot.sourceRevision != 0));
420
423 metrics_.lastSourceDeltaMs = sourceDeltaMs;
424
425 const bool sourceWasTimed = sourceTimed_;
426 bool sourceActivated = false;
427 if (!sourceTimed_ && hadSourceObservation && plausibleSourceDelta &&
428 (usesSourceRevision ? revisionAdvanced : true) && !legacyZeroTransition)
429 {
430 sourceTimed_ = true;
431 sourceActivated = true;
433 UpdateSourceCadence(static_cast<double>(sourceDeltaMs) / 1000.0);
434 ClearHistory();
435 }
436
437 if (usesSourceRevision && hadSourceObservation && (sourceWasTimed || sourceActivated))
438 {
439 if (revisionDelta == 0)
441 else if (revisionAdvanced && deliveryDelta == 1 && revisionDelta > 1)
442 metrics_.coalescedSourceRevisions += revisionDelta - 1;
443 }
444
445 const bool longSilence = sourceTimed_ && hasRawReceipt_ && rawInterval >
447 const bool impossibleActiveDelta = sourceTimed_ && !sourceActivated &&
448 (!plausibleSourceDelta || revisionMovedBackward ||
449 (usesSourceRevision && revisionAdvanced && sourceDeltaMs == 0));
450 bool reanchorSource = sourceActivated || longSilence || impossibleActiveDelta;
451
452 double timeline = receiptSeconds;
453 if (sourceTimed_)
454 {
455 if (!reanchorSource && count_ > 0)
456 {
457 timeline = SnapshotAt(count_ - 1).timelineSeconds +
458 static_cast<double>(sourceDeltaMs) / 1000.0;
459 UpdateSourceCadence(static_cast<double>(sourceDeltaMs) / 1000.0);
460 const double phaseError = receiptSeconds - timeline - sourcePhaseSeconds_;
461 const double phaseCorrection = Clamp(
465 sourcePhaseSeconds_ += phaseCorrection;
466 }
467 else
468 {
469 ClearHistory();
471 timeline = receiptSeconds;
472 if (plausibleSourceDelta)
473 UpdateSourceCadence(static_cast<double>(sourceDeltaMs) / 1000.0);
474 }
475 }
476 else if (count_ > 0)
477 {
478 const MotionSnapshot& newest = SnapshotAt(count_ - 1);
479 const double estimatedInterval = intervalInitialized_ ? metrics_.measuredIntervalSeconds :
481 const double burstSegment = Clamp(estimatedInterval * 0.5,
484 timeline = newest.timelineSeconds + burstSegment;
485 }
486
487 bool teleport = false;
488 if (count_ > 0)
489 {
490 const MotionSnapshot& newest = SnapshotAt(count_ - 1);
491 const double predictionTime = std::max(0.0, timeline - newest.timelineSeconds);
492 const PresentationState predicted = Extrapolate(newest, predictionTime);
493 metrics_.predictionErrorKm = Length(snapshot.position - predicted.position);
496 std::max(snapshot.expectedIntervalSeconds, 0.05);
497 const double teleportDistance = std::max(config_.teleportBaseDistanceKm,
499 teleport = snapshot.reference != newest.reference || snapshot.parentSlot != newest.parentSlot ||
500 snapshot.identity != newest.identity || metrics_.predictionErrorKm > teleportDistance;
501 }
502
503 if (teleport)
504 {
505 const bool identityChanged = count_ > 0 && snapshot.identity != SnapshotAt(count_ - 1).identity;
506 ClearHistory();
507 timeline = receiptSeconds;
509 if (identityChanged)
510 {
513 }
514 }
515 snapshot.timelineSeconds = timeline;
520
522 {
523 snapshots_[PhysicalIndex(count_)] = snapshot;
524 ++count_;
525 }
526 else
527 {
528 head_ = (head_ + 1) % SnapshotCapacity;
529 snapshots_[PhysicalIndex(count_ - 1)] = snapshot;
530 }
532
533 if (!teleport && lastPresentation_.valid && lastPresentationWasExtrapolated_ && rawInterval >= 0.005)
534 {
535 const double presentationClock = sourceTimed_ ? receiptSeconds - sourcePhaseSeconds_ : receiptSeconds;
536 const PresentationState target = Evaluate(presentationClock - InterpolationDelay());
537 correctionOffset_ += lastPresentation_.position - target.position;
539 }
540
542 }
543
562
571
573 const MotionSnapshot& second, double amount) const
574 {
575 PresentationState result;
576 result.valid = true;
577 result.reference = second.reference;
578 result.parentSlot = second.parentSlot;
579 result.identity = second.identity;
580 amount = Clamp(amount, 0.0, 1.0);
581 const double duration = second.timelineSeconds - first.timelineSeconds;
582 const double chordLength = Length(second.position - first.position);
583 const double tangentTravel = (Length(first.positionDerivative) + Length(second.positionDerivative)) * duration;
584 const bool validHermite = duration >= config_.minimumTimelineSegmentSeconds && duration <= 6.0 &&
585 tangentTravel <= chordLength * 8.0 + 1.0;
586 if (validHermite)
587 {
588 result.position = HermitePosition(first, second, amount, duration);
589 result.positionDerivative = HermiteVelocity(first, second, amount, duration);
590 }
591 else
592 {
593 result.position = first.position + (second.position - first.position) * amount;
595 (second.positionDerivative - first.positionDerivative) * amount;
596 }
597 result.velocity = first.velocity + (second.velocity - first.velocity) * amount;
598 result.acceleration = first.acceleration + (second.acceleration - first.acceleration) * amount;
599 result.orientation = Slerp(first.orientation, second.orientation, amount);
600 result.angularVelocity = first.angularVelocity + (second.angularVelocity - first.angularVelocity) * amount;
601 result.thrust = first.thrust + (second.thrust - first.thrust) * amount;
602 result.controlDeflection = first.controlDeflection + (second.controlDeflection - first.controlDeflection) * amount;
603 result.steerDeflection = first.steerDeflection + (second.steerDeflection - first.steerDeflection) * amount;
604 return result;
605 }
606
607 PresentationState SnapshotChannel::Extrapolate(const MotionSnapshot& snapshot, double seconds) const
608 {
609 PresentationState result;
610 result.valid = true;
611 result.reference = snapshot.reference;
612 result.parentSlot = snapshot.parentSlot;
613 result.identity = snapshot.identity;
614 result.positionDerivative = snapshot.positionDerivative;
615 result.velocity = snapshot.velocity;
616 result.acceleration = snapshot.acceleration;
617 result.angularVelocity = snapshot.angularVelocity;
618 result.thrust = snapshot.thrust;
619 result.controlDeflection = snapshot.controlDeflection;
620 result.steerDeflection = snapshot.steerDeflection;
621 result.extrapolationSeconds = std::max(0.0, seconds);
622
623 const double cap = std::max(ExtrapolationCap(), config_.minimumTimelineSegmentSeconds);
624 const double easeStart = cap * 0.75;
625 double effectiveSeconds = result.extrapolationSeconds;
626 if (effectiveSeconds > easeStart)
627 {
628 const double timeConstant = std::max(cap - easeStart, config_.minimumTimelineSegmentSeconds);
629 effectiveSeconds = easeStart + timeConstant *
630 (1.0 - std::exp(-(effectiveSeconds - easeStart) / timeConstant));
631 result.lowConfidence = true;
632 }
633 result.position = snapshot.position + snapshot.positionDerivative * effectiveSeconds;
634 result.orientation = IntegrateAngularVelocity(snapshot.orientation, snapshot.angularVelocity, effectiveSeconds);
635 return result;
636 }
637
638 PresentationState SnapshotChannel::Evaluate(double presentationSeconds) const
639 {
640 if (count_ == 0)
641 return {};
642 const MotionSnapshot& oldest = SnapshotAt(0);
643 if (count_ == 1 || presentationSeconds <= oldest.timelineSeconds)
644 return Extrapolate(oldest, 0.0);
645
646 for (std::size_t index = 1; index < count_; ++index)
647 {
648 const MotionSnapshot& second = SnapshotAt(index);
649 if (presentationSeconds <= second.timelineSeconds)
650 {
651 const MotionSnapshot& first = SnapshotAt(index - 1);
652 const double duration = second.timelineSeconds - first.timelineSeconds;
653 const double amount = duration > 0.0 ? (presentationSeconds - first.timelineSeconds) / duration : 1.0;
654 return Interpolate(first, second, amount);
655 }
656 }
657
658 const MotionSnapshot& newest = SnapshotAt(count_ - 1);
659 return Extrapolate(newest, presentationSeconds - newest.timelineSeconds);
660 }
661
662 void SnapshotChannel::AdvanceCorrection(double elapsedSeconds)
663 {
664 if (elapsedSeconds <= 0.0)
665 return;
666 const double halfLife = std::max(config_.correctionHalfLifeSeconds, 0.001);
667 const double omega = std::log(2.0) / halfLife;
668 const double decay = std::exp(-omega * elapsedSeconds);
669 auto advance = [omega, decay, elapsedSeconds](double& offset, double& velocity)
670 {
671 const double combined = velocity + omega * offset;
672 offset = (offset + combined * elapsedSeconds) * decay;
673 velocity = (velocity - omega * combined * elapsedSeconds) * decay;
674 };
678 }
679
680 PresentationState SnapshotChannel::Sample(double nowSeconds, double elapsedSeconds)
681 {
682 if (count_ == 0 || !std::isfinite(nowSeconds))
683 return {};
684 AdvanceCorrection(elapsedSeconds);
685 const double presentationClock = sourceTimed_ ? nowSeconds - sourcePhaseSeconds_ : nowSeconds;
686 PresentationState result = Evaluate(presentationClock - InterpolationDelay());
687 result.position += correctionOffset_;
690 lastPresentation_ = result;
692 return result;
693 }
694
696 {
697 ChannelMetrics result = metrics_;
698 result.snapshotDepth = count_;
701 if (count_ > 0)
702 result.newestSnapshotAgeSeconds = std::max(0.0, nowSeconds - SnapshotAt(count_ - 1).receiptSeconds);
703 return result;
704 }
705
706 bool SnapshotChannel::HasSamples() const { return count_ > 0; }
707 std::size_t SnapshotChannel::Depth() const { return count_; }
708
709 std::size_t SnapshotChannel::PhysicalIndex(std::size_t logicalIndex) const
710 {
711 return (head_ + logicalIndex) % SnapshotCapacity;
712 }
713
714 const MotionSnapshot& SnapshotChannel::SnapshotAt(std::size_t logicalIndex) const
715 {
716 assert(logicalIndex < count_);
717 return snapshots_[PhysicalIndex(logicalIndex)];
718 }
719
721 {
722 ChannelConfig vehicleConfig;
723 ChannelConfig weaponConfig = vehicleConfig;
724 weaponConfig.maximumInterpolationDelaySeconds = 0.50;
725 weaponConfig.frequentExtrapolationCapSeconds = 0.60;
726 weaponConfig.sparseExtrapolationCapSeconds = 1.00;
727 weaponConfig.teleportBaseDistanceKm = 0.20;
728 for (std::size_t index = 0; index < EntityCapacity; ++index)
729 {
730 vehicles_[index].Configure(SequenceMode::UShort, vehicleConfig);
731 weapons_[index].Configure(SequenceMode::Modulo255, weaponConfig);
732 }
733 }
734
735 void SnapshotSystem::ResetVehicle(std::size_t slot, int identity, int reference, int parentSlot, bool identityChanged)
736 {
737 if (slot < EntityCapacity)
738 vehicles_[slot].Reset(identity, reference, parentSlot, identityChanged);
739 }
740
741 void SnapshotSystem::ResetWeapon(std::size_t slot, int identity)
742 {
743 if (slot < EntityCapacity)
744 weapons_[slot].Reset(identity, -127, -1, true);
745 }
746
747 void SnapshotSystem::RemoveVehicle(std::size_t slot)
748 {
749 if (slot < EntityCapacity)
750 vehicles_[slot].Reset(0, -127, -1, false);
751 }
752
753 void SnapshotSystem::RemoveWeapon(std::size_t slot)
754 {
755 if (slot < EntityCapacity)
756 weapons_[slot].Reset(0, -127, -1, false);
757 }
758
759 Acceptance SnapshotSystem::PushVehicle(std::size_t slot, MotionSnapshot snapshot, double receiptSeconds)
760 {
761 return slot < EntityCapacity ? vehicles_[slot].Push(snapshot, receiptSeconds) : Acceptance::Invalid;
762 }
763
764 Acceptance SnapshotSystem::PushWeapon(std::size_t slot, MotionSnapshot snapshot, double receiptSeconds)
765 {
766 return slot < EntityCapacity ? weapons_[slot].Push(snapshot, receiptSeconds) : Acceptance::Invalid;
767 }
768
769 PresentationState SnapshotSystem::SampleVehicle(std::size_t slot, double nowSeconds, double elapsedSeconds)
770 {
771 return slot < EntityCapacity ? vehicles_[slot].Sample(nowSeconds, elapsedSeconds) : PresentationState{};
772 }
773
774 PresentationState SnapshotSystem::SampleWeapon(std::size_t slot, double nowSeconds, double elapsedSeconds)
775 {
776 return slot < EntityCapacity ? weapons_[slot].Sample(nowSeconds, elapsedSeconds) : PresentationState{};
777 }
778
779 ChannelMetrics SnapshotSystem::VehicleMetrics(std::size_t slot, double nowSeconds) const
780 {
781 return slot < EntityCapacity ? vehicles_[slot].GetMetrics(nowSeconds) : ChannelMetrics{};
782 }
783
784 ChannelMetrics SnapshotSystem::WeaponMetrics(std::size_t slot, double nowSeconds) const
785 {
786 return slot < EntityCapacity ? weapons_[slot].GetMetrics(nowSeconds) : ChannelMetrics{};
787 }
788
789 int SnapshotSystem::ClosestWeaponSlot(const Vec3& worldObserverPosition, const Vec3& dockObserverPosition) const
790 {
791 int closestSlot = -1;
792 double closestDistanceSquared = std::numeric_limits<double>::max();
793 for (std::size_t slot = 0; slot < EntityCapacity; ++slot)
794 {
795 if (!weapons_[slot].HasSamples())
796 continue;
797 const MotionSnapshot& snapshot = weapons_[slot].SnapshotAt(weapons_[slot].Depth() - 1);
798 const Vec3 observer = snapshot.reference < 0 ? worldObserverPosition : dockObserverPosition;
799 const Vec3 difference = snapshot.position - observer;
800 const double distanceSquared = difference.x * difference.x +
801 difference.y * difference.y + difference.z * difference.z;
802 if (distanceSquared < closestDistanceSquared)
803 {
804 closestDistanceSquared = distanceSquared;
805 closestSlot = static_cast<int>(slot);
806 }
807 }
808 return closestSlot;
809 }
810
811 bool SnapshotSystem::HasVehicleSamples(std::size_t slot) const
812 {
813 return slot < EntityCapacity && vehicles_[slot].HasSamples();
814 }
815
816 bool SnapshotSystem::HasWeaponSamples(std::size_t slot) const
817 {
818 return slot < EntityCapacity && weapons_[slot].HasSamples();
819 }
820
822}
constexpr auto Clamp(T1 val, T2 min, T3 max)
void Configure(SequenceMode sequenceMode, const ChannelConfig &config)
PresentationState Extrapolate(const MotionSnapshot &snapshot, double seconds) const
std::array< MotionSnapshot, SnapshotCapacity > snapshots_
PresentationState lastPresentation_
Acceptance Push(MotionSnapshot snapshot, double receiptSeconds)
PresentationState Evaluate(double presentationSeconds) const
ChannelMetrics GetMetrics(double nowSeconds) const
const MotionSnapshot & SnapshotAt(std::size_t logicalIndex) const
void Reset(int identity, int reference, int parentSlot, bool requireLowBootstrapSequence)
void UpdateSourceCadence(double sourceIntervalSeconds)
PresentationState Sample(double nowSeconds, double elapsedSeconds)
std::size_t PhysicalIndex(std::size_t logicalIndex) const
std::uint16_t lastObservedSourceRevision_
PresentationState Interpolate(const MotionSnapshot &first, const MotionSnapshot &second, double amount) const
void UpdateCadence(double rawIntervalSeconds)
std::uint16_t ForwardDelta(std::uint16_t incoming) const
void RecordIncoming(double receiptSeconds)
void AdvanceCorrection(double elapsedSeconds)
bool HasVehicleSamples(std::size_t slot) const
bool HasWeaponSamples(std::size_t slot) const
void ResetWeapon(std::size_t slot, int identity)
ChannelMetrics VehicleMetrics(std::size_t slot, double nowSeconds) const
void ResetVehicle(std::size_t slot, int identity, int reference, int parentSlot, bool identityChanged)
void RemoveVehicle(std::size_t slot)
Acceptance PushVehicle(std::size_t slot, MotionSnapshot snapshot, double receiptSeconds)
std::array< SnapshotChannel, EntityCapacity > vehicles_
void RemoveWeapon(std::size_t slot)
int ClosestWeaponSlot(const Vec3 &worldObserverPosition, const Vec3 &dockObserverPosition) const
PresentationState SampleVehicle(std::size_t slot, double nowSeconds, double elapsedSeconds)
std::array< SnapshotChannel, EntityCapacity > weapons_
Acceptance PushWeapon(std::size_t slot, MotionSnapshot snapshot, double receiptSeconds)
PresentationState SampleWeapon(std::size_t slot, double nowSeconds, double elapsedSeconds)
ChannelMetrics WeaponMetrics(std::size_t slot, double nowSeconds) const
float Dot(const Vector3 &a, const Vector3 &b)
constexpr double Pi
Definition OrbitMath.h:10
Quaternion Slerp(const Quaternion &aValue, const Quaternion &bValue, double amount)
double MonotonicSeconds()
Quaternion IntegrateAngularVelocity(const Quaternion &orientation, const Vec3 &angularVelocity, double seconds)
bool HasExactPayloadLength(std::size_t actualBytes, std::size_t expectedBytes)
double QuaternionLength(const Quaternion &value)
double Length(const Vec3 &value)
constexpr std::size_t SnapshotCapacity
constexpr std::size_t EntityCapacity
bool IsNewerModulo255(std::uint8_t incoming, std::uint8_t previous)
std::uint16_t SourceTimeDeltaMilliseconds(std::uint16_t incoming, std::uint16_t previous)
bool IsNewerUShort(std::uint16_t incoming, std::uint16_t previous)
Vec3 WeaponFrameEndpoint(const Vec3 &presentationPosition, const Vec3 &velocity, double elapsedSeconds, bool hasAuthoritativePresentation)
SnapshotSystem gSnapshotSystem
bool ShouldBufferVehicleReference(int reference)
bool NormalizeQuaternion(Quaternion &value)
bool IsFinite(const Vec3 &value)
double maximumSourcePhaseCorrectionPerPacketSeconds
std::uint16_t maximumBootstrapSequence
std::uint16_t lastDeliverySequenceDelta
std::uint32_t duplicateSourceRevisionCount
Vec3 & operator+=(const Vec3 &rhs)
Vec3 operator-(const Vec3 &rhs) const
Vec3 operator+(const Vec3 &rhs) const
Vec3 operator*(double scalar) const
Vec3 operator/(double scalar) const