Repository navigation
Expand file tree
/
Copy pathinput_session.go
More file actions
555 lines (502 loc) · 14.7 KB
/
Copy pathinput_session.go
File metadata and controls
555 lines (502 loc) · 14.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
/*
* 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/v4/internal/core/clock"
inputstate "github.com/goplus/spx/v4/internal/core/input"
"github.com/goplus/spx/v4/internal/engine"
)
const defaultInputSessionRandomSeed int64 = 1
// inputSessionSlot owns one game's session attachment and terminal status.
// mu also protects claim admission while a prepared session is installed.
type inputSessionSlot struct {
mu sync.RWMutex
session *inputSession
terminal InputSessionStatus
claimed bool
}
// 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
}
// inputSessionEnvironment owns deterministic process settings for one Game
// lifecycle. Rendering pace remains a project/host concern and is not changed.
type inputSessionEnvironment struct {
stopOnce sync.Once
previousFixed float64
previousFixedEnabled bool
}
// inputSession belongs to exactly one Game lifecycle.
type inputSession struct {
operationMu sync.Mutex
mu sync.Mutex
mode InputSessionMode
phase InputSessionPhase
captureKey Key
controller inputstate.InputReplayController
initialLeftPressed bool
current InputReplayState
currentTime float64
currentTick int64
hasCurrentTick bool
initialPending bool
result inputRecordingResult
abortReason string
frameOpen bool
terminalStatus InputSessionStatus
environment inputSessionEnvironment
}
// inputRecordingResult is immutable once the session has completed.
type inputRecordingResult struct {
replay InputReplay
json string
}
func (p *Game) attachPreparedInputSession() error {
// Keep slot admission locked while checking the game's loaded gate.
p.inputSlot.mu.Lock()
if p.inputSlot.claimed || p.inputSlot.session != nil {
p.inputSlot.mu.Unlock()
return ErrInputSessionActive
}
if p.lifecycle.loaded.Load() {
p.inputSlot.mu.Unlock()
return fmt.Errorf("input session must be attached before the game starts")
}
p.inputSlot.claimed = true
p.inputSlot.terminal = InputSessionStatus{}
p.inputSlot.mu.Unlock()
plan := claimPreparedInputSession()
if plan == nil {
return nil
}
defer completePreparedInputSessionClaim(plan)
session, err := newInputSession(plan)
if err != nil {
p.inputSlot.setTerminal(InputSessionStatus{
Mode: plan.mode,
Phase: InputSessionPhaseAborted,
Error: err.Error(),
})
return err
}
if !p.inputSlot.attach(session) {
p.inputSlot.setTerminal(session.close("another input session is already attached"))
return fmt.Errorf("game lifecycle ended before input session attachment completed")
}
return nil
}
func (p *Game) inputSessionUnavailable() bool {
if p == nil {
return false
}
p.inputSlot.mu.RLock()
unavailable := p.inputSlot.claimed || p.lifecycle.loaded.Load()
p.inputSlot.mu.RUnlock()
return unavailable
}
func (p *Game) currentInputSession() *inputSession {
if p == nil {
return nil
}
return p.inputSlot.current()
}
func (p *Game) abortInputSession(reason string) {
if p == nil {
return
}
p.inputSlot.abort(reason)
}
func (p *Game) terminalInputSessionStatus() (InputSessionStatus, bool) {
return p.inputSlot.terminalStatus()
}
func (p *Game) finishInputSessionFrame() {
session := p.currentInputSession()
if session == nil {
return
}
session.endFrame()
if _, err := session.completeReplayFrame(engine.Managers().ExtMgr.Pause); err != nil {
engine.Panic(err)
}
}
func (s *inputSessionSlot) attach(session *inputSession) bool {
s.mu.Lock()
defer s.mu.Unlock()
if !s.claimed || s.session != nil {
return false
}
s.session = session
return true
}
func (s *inputSessionSlot) current() *inputSession {
s.mu.RLock()
session := s.session
s.mu.RUnlock()
return session
}
func (s *inputSessionSlot) abort(reason string) {
s.mu.Lock()
if s.session != nil {
s.terminal = s.session.close(reason)
s.session = nil
}
s.claimed = false
s.mu.Unlock()
}
func (s *inputSessionSlot) setTerminal(status InputSessionStatus) {
s.mu.Lock()
s.session = nil
s.terminal = status
s.mu.Unlock()
}
func (s *inputSessionSlot) terminalStatus() (InputSessionStatus, bool) {
s.mu.RLock()
status := s.terminal
s.mu.RUnlock()
return status, status.Phase != ""
}
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 = inputRecordingResult{}
}
status := s.statusLocked()
s.terminalStatus = status
s.controller.Reset()
s.mu.Unlock()
s.operationMu.Unlock()
s.environment.stop()
ResetRandomSeed()
engine.DiscardPendingKeyEvents()
engine.DiscardPendingMouseEvents()
return status
}
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 := s.result
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
}
// Recording returns an owned snapshot; keep it as the cache until finishing succeeds.
s.result = inputRecordingResult{replay: replay, json: string(encoded)}
s.mu.Unlock()
if err := freezeInputSession(freeze); err != nil {
s.mu.Lock()
s.result = inputRecordingResult{}
s.phase = InputSessionPhaseRunning
s.mu.Unlock()
return inputRecordingResult{}, err
}
s.mu.Lock()
s.phase = InputSessionPhaseCompleted
result := s.result
s.mu.Unlock()
return result, nil
}
func (s *inputSession) status() InputSessionStatus {
s.mu.Lock()
defer s.mu.Unlock()
return s.statusLocked()
}
func (s *inputSession) statusLocked() InputSessionStatus {
if s.terminalStatus.Phase != "" {
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.replay.Frames))
status.FrameCount = len(s.result.replay.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) completeReplayFrame(freeze func()) (bool, error) {
s.operationMu.Lock()
defer s.operationMu.Unlock()
s.mu.Lock()
if s.mode != InputSessionModeReplaying || s.phase != InputSessionPhaseFinishing || !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 (e *inputSessionEnvironment) start(fixedTimestep float64) {
e.previousFixed, e.previousFixedEnabled = clock.FixedDeltaTime()
clock.SetFixedDeltaTime(fixedTimestep)
}
func (e *inputSessionEnvironment) stop() {
e.stopOnce.Do(func() {
if e.previousFixedEnabled {
clock.SetFixedDeltaTime(e.previousFixed)
} else {
clock.SetFixedDeltaTime(0)
}
})
}
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: inputstate.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 := currentGame(); 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 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) (*inputSession, error) {
session := &inputSession{
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.initialLeftPressed = plan.replay.Initial.Buttons&1 != 0
session.current = inputstate.CloneInputReplayState(plan.replay.Initial)
default:
return nil, fmt.Errorf("unsupported input session mode %q", plan.mode)
}
engine.DiscardPendingKeyEvents()
engine.DiscardPendingMouseEvents()
session.environment.start(fixedTimestep)
setDeterministicRandomSeed(defaultInputSessionRandomSeed)
return session, nil
}
func finishInputRecording() (inputRecordingResult, error) {
game := currentGame()
if game == nil {
return inputRecordingResult{}, ErrInputSessionNotRecording
}
session := game.currentInputSession()
if session == nil {
return inputRecordingResult{}, ErrInputSessionNotRecording
}
var freeze func()
if game.lifecycle.loaded.Load() {
freeze = engine.Managers().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 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
}
func activeInputSession() *inputSession {
if game := currentGame(); 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 := currentGame(); game != nil {
if status, ok := game.terminalInputSessionStatus(); ok {
return status
}
}
return InputSessionStatus{Mode: InputSessionModeIdle}
}