-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMotionSDK.swift
More file actions
255 lines (231 loc) · 7.93 KB
/
Copy pathMotionSDK.swift
File metadata and controls
255 lines (231 loc) · 7.93 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
import Foundation
import Combine
/// Fasada Motion SDK: pozycja, gest rzutu, przycisk BLE → `GameInput`.
@MainActor
/// Represents motion sdk.
public final class MotionSDK: ObservableObject {
/// Stores `processor` used by this scope.
let processor = MotionProcessor()
/// Stores `gesture` used by this scope.
let gesture = GestureDetector()
/// Stores `button` used by this scope.
let button = ButtonDetector()
/// Współdzielony silnik przetwarzania ruchu.
public let engine: MotionEngine
/// Ostatni bajt przycisku BLE (DEV).
public var lastButtonByte: UInt8 { button.lastSeenButtonByte }
/// Czy oczekuje nieodebrany impuls przycisku (DEV).
public var hasPendingButtonClick: Bool { button.didClick }
/// Ostatnia opublikowana ramka wejścia.
public private(set) var input = GameInput()
// MARK: - BLE (connect + pollInput)
/// Stan połączenia BLE.
@Published public internal(set) var isConnected = false
/// Informuje, czy napływają pakiety BLE.
@Published public internal(set) var isReceiving = false
/// Wykryty tryb częstotliwości notify (fast / normal / low power).
@Published public internal(set) var trikiBLEMode: TrikiBLEMode = .unknown
/// Podpowiedź UX przy low power (np. „czeka na ruch”).
@Published public internal(set) var trikiIdleStatusMessage: String? = nil
/// Ostatnia ramka wejścia publikowana do HUD.
@Published public internal(set) var liveInput = GameInput()
/// Stores `bleManager` used by this scope.
var bleManager: TrikiBLEManager?
/// Gamepad pipeline (parser + motion engine).
var trikiController: TrikiGameController?
/// Stores `streamParser` used by this scope.
var streamParser: MotionParser?
/// Stores `bleCancellables` used by this scope.
var bleCancellables = Set<AnyCancellable>()
/// Stores `lastPacketAt` used by this scope.
var lastPacketAt: TimeInterval = 0
/// Stores `lastHudPublishAt` used by this scope.
var lastHudPublishAt: TimeInterval = 0
/// Stores `latestEnrichedInput` used by this scope.
var latestEnrichedInput = GameInput()
/// Konfiguracja silnika ruchu.
public var config: MotionConfig {
get { engine.config }
set { engine.config = newValue }
}
/// Aktualny tryb sterowania.
public var mode: MotionMode {
get { engine.config.mode }
set { engine.setMode(newValue) }
}
/// Ostatni wynik ruchu z silnika.
public var output: MotionOutput { engine.output }
/// Ostatnie dane debugowe z silnika.
public var debug: MotionDebug { engine.debug }
private var rxBuffer: [UInt8] = []
private var lastPollTime: TimeInterval?
private var ingressRotation = 0.0
private var ingressTiltX = 0.0
private var ingressGyroY = 0.0
private var latestPaddleRaw: Double?
var lastFramePosX: Double?
var lastFramePosY: Double?
/// Ostatni `bytes[1]` przy ostatnim `pollInput` (zbocze między pollami).
var lastSampledButtonByte: UInt8 = 0
/// Dev Mode / HUD: trzyma `bleButtonClick` przez krótki czas po zboczu.
var buttonClickHighlightUntil: TimeInterval = 0
/// Tworzy instancję SDK ruchu.
public init() {
engine = MotionEngine(processor: processor, gesture: gesture)
}
/// Ustawia tryb pracy silnika.
public func setMode(_ mode: MotionMode) {
engine.setMode(mode)
}
/// Ustawia dodatkowe źródła wejścia podawane spoza BLE.
public func setIngressSupplement(rotation: Double, tiltX: Double, gyroY: Double) {
ingressRotation = rotation
ingressTiltX = tiltX
ingressGyroY = gyroY
}
/// BLE callback — buforuje bajty (przycisk) i rawX w trybie paletki.
public func enqueueBLE(_ data: [UInt8]) {
guard !data.isEmpty else { return }
button.process(data)
if engine.config.mode == .paddle {
if let raw = BLEGyroParser.gyroRawFromPacket(data) {
latestPaddleRaw = raw
}
return
}
rxBuffer.append(contentsOf: data)
if rxBuffer.count > 512 {
rxBuffer.removeSubrange(0..<(rxBuffer.count - 256))
}
}
/// Handles `flushIngress`.
public func flushIngress() {
if engine.config.mode == .paddle {
if let raw = latestPaddleRaw {
engine.setRawX(raw)
}
return
}
let cfg = engine.config
var tiltBlock: BLEGyroParser.GyroTriple?
var gyroBlock: BLEGyroParser.GyroTriple?
var blockIndex = 0
if !rxBuffer.isEmpty {
let blocks = BLEGyroParser.drainGyroBlocks(from: &rxBuffer)
if !blocks.isEmpty {
if let first = blocks.first {
tiltBlock = BLEGyroParser.scaledTiltBlock(first)
}
if blocks.count >= 2 {
gyroBlock = blocks[blocks.count - 1]
blockIndex = blocks.count - 1
}
}
}
let gx = gyroBlock?.x ?? tiltBlock?.x ?? ingressTiltX
let gy = gyroBlock?.y ?? tiltBlock?.y ?? ingressGyroY
let gz = gyroBlock?.z ?? tiltBlock?.z ?? 0
let mapped = cfg.axisMapping.map(
gx: gx,
gy: gy,
gz: gz,
rotation: ingressRotation
)
engine.setPaddleSources(rotation: mapped.x, gyroZ: gz)
engine.updateRaw(x: mapped.x, y: mapped.y, gyroBlockIndex: blockIndex)
}
/// Podaje do SDK zdekodowaną ramkę Triki.
public func ingestTrikiFrame(
gyroX: Double,
gyroY: Double,
gyroZ: Double,
rotation: Double
) {
ingressRotation = rotation
ingressGyroY = gyroY
let mapping = engine.config.axisMapping
let mapped = mapping.map(gx: gyroX, gy: gyroY, gz: gyroZ, rotation: rotation)
engine.setPaddleSources(rotation: mapped.x, gyroZ: gyroZ)
if engine.config.mode == .paddle {
latestPaddleRaw = mapped.x * BLEGyroParser.gyroDivisor
} else {
engine.updateRaw(x: mapped.x, y: mapped.y, gyroBlockIndex: 1)
}
}
/// Aktualizacja klatki: opcjonalnie surowy X i pakiet BLE (przycisk).
///
/// - Parameters:
/// - rawX: Optional raw X sample forwarded directly to motion engine.
/// - bytes: Optional BLE payload slice used for button decoding.
/// - deltaTime: Optional frame delta in seconds overriding internal timing.
/// - Returns: Motion output produced for the updated frame.
@discardableResult
/// Convenience frame update entrypoint with optional raw input and BLE packet payload.
public func update(
rawX: Double? = nil,
bytes: [UInt8] = [],
deltaTime: TimeInterval? = nil
) -> MotionOutput {
if let rawX {
engine.setRawX(rawX)
}
if !bytes.isEmpty {
button.process(bytes)
}
return updateFrame(deltaTime: deltaTime)
}
/// Aktualizuje silnik i zwraca wynik aktualnej klatki.
@discardableResult
/// Handles `updateFrame`.
///
/// - Parameters:
/// - deltaTime: Input used by this operation.
/// - Returns: Result produced by this operation.
public func updateFrame(deltaTime: TimeInterval? = nil) -> MotionOutput {
flushIngress()
let now = Date().timeIntervalSince1970
let dt: TimeInterval
if let deltaTime {
dt = deltaTime
} else {
dt = min(0.05, max(0, now - (lastPollTime ?? now)))
}
lastPollTime = now
engine.updateFrame(deltaTime: dt)
publishInput()
return engine.output
}
/// Resetuje pełny stan SDK i silnika.
public func reset() {
rxBuffer.removeAll(keepingCapacity: false)
lastPollTime = nil
ingressRotation = 0
ingressTiltX = 0
ingressGyroY = 0
latestPaddleRaw = nil
lastFramePosX = nil
lastFramePosY = nil
lastSampledButtonByte = 0
buttonClickHighlightUntil = 0
button.reset()
engine.resetState()
input = GameInput()
}
private func publishInput() {
let out = engine.output
let trikiAction = trikiController?.gameInput.isAction ?? false
let throwShot = out.didShoot
input.posX = out.x
input.posY = out.y
input.shotTriggered = throwShot
input.bleButtonClick = false
switch engine.config.mode {
case .paddle:
input.primaryAction = false
case .pointer, .gesture:
input.primaryAction = throwShot || trikiAction
}
input.throwPower = throwShot ? engine.lastGestureThrowPower : 0
input.gesturePrimed = engine.gesturePrimed
}
}