Repository navigation
Expand file tree
/
Copy pathruntime_replay_session.go
More file actions
584 lines (532 loc) · 15.7 KB
/
Copy pathruntime_replay_session.go
File metadata and controls
584 lines (532 loc) · 15.7 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
/*
* Copyright (c) 2021 The XGo Authors (xgo.dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spx
import (
"fmt"
"sync"
"github.com/goplus/spx/v3/internal/engine"
inputstate "github.com/goplus/spx/v3/internal/input"
)
const defaultInputSessionRandomSeed int64 = 1
// inputSessionPlan is an immutable, one-shot descriptor for the next game
// lifecycle. Runtime state is created only after a Game claims the plan.
type inputSessionPlan struct {
token uint64
mode InputSessionMode
fixedTimestep float64
replay InputReplay
captureKey Key
}
var preparedInputSession struct {
sync.Mutex
nextToken uint64
plan *inputSessionPlan
claimed bool
}
// inputSession belongs to exactly one Game bootstrap generation.
type inputSession struct {
operationMu sync.Mutex
mu sync.Mutex
generation uint64
mode InputSessionMode
phase InputSessionPhase
captureKey Key
controller inputstate.InputReplayController
initial InputReplayState
current InputReplayState
currentTime float64
currentTick int64
hasCurrentTick bool
initialPending bool
result InputReplay
resultJSON []byte
abortReason string
frameOpen bool
terminalStatus InputSessionStatus
hasTerminal bool
input inputSessionInput
environment inputSessionEnvironment
}
type inputRecordingResult struct {
replay InputReplay
json []byte
}
func prepareInputRecordingSession(fixedTimestep float64, option InputSessionOptions) (InputSessionPreparation, error) {
return prepareInputSession(inputSessionPlan{
mode: InputSessionModeRecording,
fixedTimestep: fixedTimestep,
captureKey: option.CaptureKey,
})
}
func prepareInputReplaySession(replay InputReplay, option InputSessionOptions) (InputSessionPreparation, error) {
if err := replay.Validate(); err != nil {
return InputSessionPreparation{}, err
}
return prepareInputSession(inputSessionPlan{
mode: InputSessionModeReplaying,
replay: cloneInputReplay(replay),
captureKey: option.CaptureKey,
})
}
func prepareInputSession(plan inputSessionPlan) (InputSessionPreparation, error) {
preparedInputSession.Lock()
defer preparedInputSession.Unlock()
if preparedInputSession.plan != nil {
return InputSessionPreparation{}, ErrInputSessionActive
}
if game := activeGame(); game != nil {
if game.inputSessionUnavailable() {
return InputSessionPreparation{}, ErrInputSessionActive
}
}
preparedInputSession.nextToken++
if preparedInputSession.nextToken == 0 {
preparedInputSession.nextToken++
}
plan.token = preparedInputSession.nextToken
preparedInputSession.plan = &plan
preparedInputSession.claimed = false
return InputSessionPreparation{token: plan.token}, nil
}
func claimPreparedInputSession() *inputSessionPlan {
preparedInputSession.Lock()
defer preparedInputSession.Unlock()
if preparedInputSession.plan == nil || preparedInputSession.claimed {
return nil
}
preparedInputSession.claimed = true
return preparedInputSession.plan
}
func completePreparedInputSessionClaim(plan *inputSessionPlan) {
preparedInputSession.Lock()
if preparedInputSession.plan == plan {
preparedInputSession.plan = nil
preparedInputSession.claimed = false
}
preparedInputSession.Unlock()
}
func cancelPreparedInputSession(token uint64) bool {
preparedInputSession.Lock()
defer preparedInputSession.Unlock()
if token == 0 || preparedInputSession.plan == nil || preparedInputSession.claimed || preparedInputSession.plan.token != token {
return false
}
preparedInputSession.plan = nil
return true
}
func clearPreparedInputSession() {
preparedInputSession.Lock()
preparedInputSession.plan = nil
preparedInputSession.claimed = false
preparedInputSession.Unlock()
}
func preparedInputSessionStatus() (InputSessionStatus, bool) {
preparedInputSession.Lock()
defer preparedInputSession.Unlock()
if preparedInputSession.plan == nil {
return InputSessionStatus{}, false
}
status := InputSessionStatus{
Mode: preparedInputSession.plan.mode,
Phase: InputSessionPhasePrepared,
}
if status.Mode == InputSessionModeReplaying {
status.FrameCount = len(preparedInputSession.plan.replay.Frames)
}
return status, true
}
func newInputSession(plan *inputSessionPlan, generation uint64) (*inputSession, error) {
session := &inputSession{
generation: generation,
mode: plan.mode,
phase: InputSessionPhaseRunning,
captureKey: plan.captureKey,
}
var fixedTimestep float64
switch plan.mode {
case InputSessionModeRecording:
fixedTimestep = plan.fixedTimestep
if err := session.controller.StartRecording(InputReplayState{}, fixedTimestep); err != nil {
return nil, err
}
session.initialPending = true
case InputSessionModeReplaying:
if err := session.controller.StartReplay(plan.replay); err != nil {
return nil, err
}
fixedTimestep = plan.replay.FixedTimestep
session.initial = cloneInputReplayState(plan.replay.Initial)
session.current = cloneInputReplayState(plan.replay.Initial)
default:
return nil, fmt.Errorf("unsupported input session mode %q", plan.mode)
}
engine.DiscardPendingKeyEvents()
session.environment.start(fixedTimestep)
setDeterministicRandomSeed(defaultInputSessionRandomSeed)
engine.SetMouseEventCaptureEnabled(true)
return session, nil
}
func (p *Game) attachPreparedInputSession() error {
p.inputSessionMu.Lock()
if p.inputClaimed || p.inputSession != nil {
p.inputSessionMu.Unlock()
return ErrInputSessionActive
}
if p.lifecycleState.IsRunned.Load() {
p.inputSessionMu.Unlock()
return fmt.Errorf("input session must be attached before the game starts")
}
p.inputClaimed = true
p.hasInputTerm = false
p.inputTerminal = InputSessionStatus{}
p.inputSessionMu.Unlock()
plan := claimPreparedInputSession()
if plan == nil {
return nil
}
session, err := newInputSession(plan, p.currentBootstrapGeneration())
if err != nil {
p.setInputSessionTerminal(InputSessionStatus{
Mode: plan.mode,
Phase: InputSessionPhaseAborted,
Error: err.Error(),
})
completePreparedInputSessionClaim(plan)
return err
}
p.inputSessionMu.Lock()
if !p.inputClaimed || p.inputSession != nil {
p.inputSessionMu.Unlock()
p.setInputSessionTerminal(session.close("another input session is already attached"))
completePreparedInputSessionClaim(plan)
return fmt.Errorf("game lifecycle ended before input session attachment completed")
}
p.inputSession = session
p.inputSessionMu.Unlock()
completePreparedInputSessionClaim(plan)
return nil
}
func (p *Game) inputSessionUnavailable() bool {
if p == nil {
return false
}
p.inputSessionMu.RLock()
unavailable := p.inputClaimed || p.lifecycleState.IsRunned.Load()
p.inputSessionMu.RUnlock()
return unavailable
}
func (p *Game) currentInputSession() *inputSession {
if p == nil {
return nil
}
p.inputSessionMu.RLock()
session := p.inputSession
p.inputSessionMu.RUnlock()
return session
}
func (p *Game) abortInputSession(reason string) {
if p == nil {
return
}
p.inputSessionMu.Lock()
if p.inputSession != nil {
p.inputTerminal = p.inputSession.close(reason)
p.hasInputTerm = true
p.inputSession = nil
}
p.inputClaimed = false
p.inputSessionMu.Unlock()
}
func (p *Game) setInputSessionTerminal(status InputSessionStatus) {
p.inputSessionMu.Lock()
p.inputSession = nil
p.inputTerminal = status
p.hasInputTerm = true
p.inputSessionMu.Unlock()
}
func (p *Game) terminalInputSessionStatus() (InputSessionStatus, bool) {
p.inputSessionMu.RLock()
status, ok := p.inputTerminal, p.hasInputTerm
p.inputSessionMu.RUnlock()
return status, ok
}
func (s *inputSession) close(reason string) InputSessionStatus {
s.operationMu.Lock()
s.mu.Lock()
if s.phase != InputSessionPhaseCompleted && s.phase != InputSessionPhaseAborted {
s.phase = InputSessionPhaseAborted
s.abortReason = reason
s.result = InputReplay{}
s.resultJSON = nil
}
status := s.statusLocked()
s.terminalStatus = status
s.hasTerminal = true
s.controller.Reset()
s.mu.Unlock()
s.operationMu.Unlock()
s.environment.stop()
ResetRandomSeed()
engine.DiscardPendingKeyEvents()
engine.SetMouseEventCaptureEnabled(false)
return status
}
func finishInputRecordingResultSession() (inputRecordingResult, error) {
game := activeGame()
if game == nil {
return inputRecordingResult{}, ErrInputSessionNotRecording
}
session := game.currentInputSession()
if session == nil {
return inputRecordingResult{}, ErrInputSessionNotRecording
}
var freeze func()
if game.lifecycleState.IsRunned.Load() {
freeze = func() { game.engine().ExtMgr.Pause() }
}
result, err := session.finishRecordingResult(freeze)
if err != nil && freeze != nil {
// Finish is the host's Game-stop boundary. Even an uncommittable
// recording must be quiesced so capture draining cannot be starved by
// later frames while shutdown reports the original error.
_ = freezeInputSession(freeze)
}
return result, err
}
func finishInputRecordingSession() (InputReplay, error) {
result, err := finishInputRecordingResultSession()
return result.replay, err
}
func finishInputRecordingJSONSession() (string, error) {
result, err := finishInputRecordingResultSession()
return string(result.json), err
}
func (s *inputSession) finishRecording(freeze func()) (InputReplay, error) {
result, err := s.finishRecordingResult(freeze)
return result.replay, err
}
func (s *inputSession) finishRecordingResult(freeze func()) (inputRecordingResult, error) {
s.operationMu.Lock()
defer s.operationMu.Unlock()
s.mu.Lock()
if s.mode != InputSessionModeRecording {
s.mu.Unlock()
return inputRecordingResult{}, ErrInputSessionNotRecording
}
if s.phase == InputSessionPhaseAborted {
reason := s.abortReason
s.mu.Unlock()
return inputRecordingResult{}, fmt.Errorf("input recording was aborted: %s", reason)
}
if s.phase == InputSessionPhaseCompleted {
result := inputRecordingResult{
replay: cloneInputReplay(s.result),
json: append([]byte(nil), s.resultJSON...),
}
s.mu.Unlock()
return result, nil
}
if s.phase != InputSessionPhaseRunning {
phase := s.phase
s.mu.Unlock()
return inputRecordingResult{}, fmt.Errorf("input recording cannot finish in phase %q", phase)
}
if s.frameOpen {
s.mu.Unlock()
return inputRecordingResult{}, fmt.Errorf("input recording cannot finish before the current frame ends")
}
s.phase = InputSessionPhaseFinishing
replay, err := s.controller.Recording()
if err != nil {
s.phase = InputSessionPhaseRunning
s.mu.Unlock()
return inputRecordingResult{}, err
}
encoded, err := inputstate.EncodeInputReplay(replay)
if err != nil {
s.phase = InputSessionPhaseRunning
s.mu.Unlock()
return inputRecordingResult{}, err
}
s.result = cloneInputReplay(replay)
s.resultJSON = append(s.resultJSON[:0], encoded...)
s.mu.Unlock()
if err := freezeInputSession(freeze); err != nil {
s.mu.Lock()
s.result = InputReplay{}
s.resultJSON = nil
s.phase = InputSessionPhaseRunning
s.mu.Unlock()
return inputRecordingResult{}, err
}
s.mu.Lock()
s.phase = InputSessionPhaseCompleted
s.mu.Unlock()
return inputRecordingResult{replay: replay, json: encoded}, nil
}
func freezeInputSession(freeze func()) (err error) {
if freeze == nil {
return nil
}
defer func() {
if recovered := recover(); recovered != nil {
err = fmt.Errorf("freeze input session: %v", recovered)
}
}()
freeze()
return nil
}
// resetInputSessionState is retained as an internal cleanup seam. Product
// callers end the Game instead of resetting input independently.
func resetInputSessionState() {
clearPreparedInputSession()
if game := activeGame(); game != nil {
game.abortInputSession("input session reset")
game.inputSessionMu.Lock()
game.inputTerminal = InputSessionStatus{}
game.hasInputTerm = false
game.inputSessionMu.Unlock()
}
}
func activeInputSession() *inputSession {
if game := activeGame(); game != nil {
return game.currentInputSession()
}
return nil
}
func inputSessionStatus() InputSessionStatus {
// The prepared descriptor remains visible until its Game-owned session is
// installed. Reading it first makes the handoff monotonic: Prepared never
// briefly appears as Idle while startup polling is in progress.
if status, ok := preparedInputSessionStatus(); ok {
return status
}
if session := activeInputSession(); session != nil {
return session.status()
}
if game := activeGame(); game != nil {
if status, ok := game.terminalInputSessionStatus(); ok {
return status
}
}
return InputSessionStatus{Mode: InputSessionModeIdle}
}
func (s *inputSession) status() InputSessionStatus {
s.mu.Lock()
defer s.mu.Unlock()
return s.statusLocked()
}
func (s *inputSession) statusLocked() InputSessionStatus {
if s.hasTerminal {
return s.terminalStatus
}
controllerStatus := s.controller.Status()
status := InputSessionStatus{
Mode: s.mode,
Phase: s.phase,
Completed: s.phase == InputSessionPhaseCompleted,
Exhausted: controllerStatus.Exhausted,
NextFrame: controllerStatus.NextFrame,
FrameCount: controllerStatus.FrameCount,
}
if s.hasCurrentTick {
status.CurrentTick = s.currentTick
status.HasCurrentTick = true
}
if s.mode == InputSessionModeRecording && s.phase == InputSessionPhaseCompleted {
status.NextFrame = int64(len(s.result.Frames))
status.FrameCount = len(s.result.Frames)
}
if s.phase == InputSessionPhaseAborted {
status.Error = s.abortReason
}
return status
}
func (s *inputSession) beginFrame() bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.phase != InputSessionPhaseRunning || s.frameOpen {
return false
}
s.frameOpen = true
return true
}
func (s *inputSession) endFrame() {
s.mu.Lock()
s.frameOpen = false
s.mu.Unlock()
}
func (s *inputSession) frameCompletionPending() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.mode == InputSessionModeReplaying && s.phase == InputSessionPhaseFinishing
}
func (p *Game) inputSessionFrameCompletionPending() bool {
session := p.currentInputSession()
return session != nil && session.frameCompletionPending()
}
func (p *Game) finishInputSessionFrame() {
session := p.currentInputSession()
if session == nil {
return
}
session.endFrame()
completed, err := session.completeReplayFrame(func() { p.engine().ExtMgr.Pause() })
if err != nil {
engine.Panic(err)
return
}
if !completed {
return
}
}
func (s *inputSession) completeReplayFrame(freeze func()) (bool, error) {
s.operationMu.Lock()
defer s.operationMu.Unlock()
s.mu.Lock()
if s.mode != InputSessionModeReplaying || s.phase != InputSessionPhaseFinishing {
s.mu.Unlock()
return false, nil
}
if !s.controller.Status().Exhausted {
s.mu.Unlock()
return false, nil
}
s.mu.Unlock()
if err := freezeInputSession(freeze); err != nil {
s.mu.Lock()
s.phase = InputSessionPhaseAborted
s.abortReason = err.Error()
s.mu.Unlock()
return false, err
}
s.mu.Lock()
s.phase = InputSessionPhaseCompleted
s.mu.Unlock()
return true, nil
}
func cloneInputReplay(replay InputReplay) InputReplay {
cloned := replay
cloned.Initial = cloneInputReplayState(replay.Initial)
cloned.Frames = make([]InputReplayFrame, len(replay.Frames))
for i, frame := range replay.Frames {
cloned.Frames[i] = frame
cloned.Frames[i].State = cloneInputReplayState(frame.State)
cloned.Frames[i].MouseEvents = append([]InputReplayMouseEvent(nil), frame.MouseEvents...)
cloned.Frames[i].KeyEvents = append([]InputReplayKeyEvent(nil), frame.KeyEvents...)
}
return cloned
}