-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
race_control.go
1460 lines (1112 loc) · 41.5 KB
/
race_control.go
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
package servermanager
import (
"context"
"fmt"
"math"
"path/filepath"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/mitchellh/go-wordwrap"
"github.com/sirupsen/logrus"
lua "github.com/yuin/gopher-lua"
"github.com/JustaPenguin/assetto-server-manager/pkg/udp"
)
type RaceControl struct {
process ServerProcess
store Store
penaltiesManager *PenaltiesManager
SessionInfo udp.SessionInfo `json:"SessionInfo"`
TrackMapData TrackMapData `json:"TrackMapData"`
TrackInfo TrackInfo `json:"TrackInfo"`
SessionStartTime time.Time `json:"SessionStartTime"`
CurrentRealtimePosInterval int `json:"CurrentRealtimePosInterval"`
ChatMessages []udp.Chat
ChatMessagesMutex sync.Mutex
ConnectedDrivers *DriverMap `json:"ConnectedDrivers"`
DisconnectedDrivers *DriverMap `json:"DisconnectedDrivers"`
CarIDToGUID map[udp.CarID]udp.DriverGUID `json:"CarIDToGUID"`
carIDToGUIDMutex sync.RWMutex
carUpdaters map[udp.CarID]chan udp.CarUpdate
serverProcessStopped chan struct{}
broadcaster Broadcaster
trackDataGateway TrackDataGateway
currentTimeAttackEvent *CustomRace
lastUpdateMessage []byte
lastUpdateMessageMutex sync.Mutex
persistStoreDataMutex sync.Mutex
// driver swap
driverSwapTimers map[int]*time.Timer
driverSwapPenaltiesMutex sync.Mutex
driverSwapPenalties map[udp.DriverGUID]*driverSwapPenalty
}
// RaceControl piggyback's on the udp.Message interface so that the entire data can be sent to newly connected clients.
func (rc *RaceControl) Event() udp.Event {
return 200
}
type CollisionType string
const (
CollisionWithCar CollisionType = "with other car"
CollisionWithEnvironment CollisionType = "with environment"
)
type Collision struct {
ID string `json:"ID"`
Type CollisionType `json:"Type"`
Time time.Time `json:"Time" ts:"date"`
OtherDriverGUID udp.DriverGUID `json:"OtherDriverGUID"`
OtherDriverName string `json:"OtherDriverName"`
Speed float64 `json:"Speed"`
}
func NewRaceControl(broadcaster Broadcaster, trackDataGateway TrackDataGateway, process ServerProcess, store Store, penaltiesManager *PenaltiesManager) *RaceControl {
rc := &RaceControl{
broadcaster: broadcaster,
trackDataGateway: trackDataGateway,
process: process,
store: store,
driverSwapTimers: make(map[int]*time.Timer),
penaltiesManager: penaltiesManager,
carUpdaters: make(map[udp.CarID]chan udp.CarUpdate),
serverProcessStopped: make(chan struct{}),
}
process.NotifyDone(rc.serverProcessStopped)
rc.clearAllDrivers()
go panicCapture(rc.watchForTimedOutDrivers)
return rc
}
func (rc *RaceControl) UDPCallback(message udp.Message) {
var err error
sendUpdatedRaceControlStatus := false
switch m := message.(type) {
case udp.Version:
err = rc.OnVersion(m)
case udp.SessionInfo:
if m.Event() == udp.EventNewSession {
err = rc.OnNewSession(m)
sendUpdatedRaceControlStatus = true
} else {
sendUpdatedRaceControlStatus, err = rc.OnSessionUpdate(m)
}
case udp.EndSession:
err = rc.OnEndSession(m)
sendUpdatedRaceControlStatus = true
case udp.CarUpdate:
err = rc.OnCarUpdate(m)
case udp.SessionCarInfo:
if m.Event() == udp.EventNewConnection {
err = rc.OnClientConnect(m)
} else if m.Event() == udp.EventConnectionClosed {
err = rc.OnClientDisconnect(m)
}
sendUpdatedRaceControlStatus = true
case udp.ClientLoaded:
err = rc.OnClientLoaded(m)
sendUpdatedRaceControlStatus = true
case udp.CollisionWithCar:
err = rc.OnCollisionWithCar(m)
sendUpdatedRaceControlStatus = true
case udp.CollisionWithEnvironment:
err = rc.OnCollisionWithEnvironment(m)
sendUpdatedRaceControlStatus = true
case udp.LapCompleted:
err = rc.OnLapCompleted(m)
sendUpdatedRaceControlStatus = true
case udp.Chat:
// received a chat message
var driver *RaceControlDriver
driver, err = rc.findConnectedDriverByCarID(m.CarID)
if err == nil {
m.DriverGUID = driver.CarInfo.DriverGUID
m.DriverName = driver.CarInfo.DriverName
} else if m.DriverGUID == "" && m.DriverName == "" {
m.DriverGUID = "0"
m.DriverName = "Server"
}
m.Time = time.Now()
err = rc.OnChatMessage(m)
default:
return
}
if err != nil {
logrus.WithError(err).Errorf("Unable to handle event: %d", message.Event())
return
}
if sendUpdatedRaceControlStatus {
// update the current refresh rate
rc.CurrentRealtimePosInterval = udp.CurrentRealtimePosIntervalMs
lastUpdateMessage, err := rc.broadcaster.Send(rc)
if err != nil {
logrus.WithError(err).Error("Unable to broadcast race control message")
return
}
rc.lastUpdateMessageMutex.Lock()
rc.lastUpdateMessage = lastUpdateMessage
rc.lastUpdateMessageMutex.Unlock()
}
}
var driverTimeout = time.Minute * 5
func (rc *RaceControl) watchForTimedOutDrivers() {
if udp.RealtimePosIntervalMs <= 0 {
// with no real time pos interval, we have no driver positions, so no last update time.
return
}
ticker := time.NewTicker(time.Minute)
for range ticker.C {
var driversToDisconnect []*RaceControlDriver
_ = rc.ConnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
driver.mutex.Lock()
defer driver.mutex.Unlock()
if !driver.LastSeen.IsZero() && time.Since(driver.LastSeen) > driverTimeout || driver.LastSeen.IsZero() && time.Since(driver.ConnectedTime) > driverTimeout {
driversToDisconnect = append(driversToDisconnect, driver)
}
return nil
})
for _, driver := range driversToDisconnect {
logrus.Debugf("Driver: %s (%s) has not been seen in 5 minutes, disconnecting", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID)
err := rc.disconnectDriver(driver)
if err != nil {
logrus.WithError(err).Errorf("Could not disconnect driver: %s (%s)", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID)
continue
}
}
if len(driversToDisconnect) > 0 {
_, err := rc.broadcaster.Send(rc)
if err != nil {
logrus.WithError(err).Error("Could not broadcast driver disconnect message")
}
}
}
}
// OnVersion occurs when the Assetto Corsa Server starts up for the first time.
func (rc *RaceControl) OnVersion(version udp.Version) error {
go panicCapture(rc.requestSessionInfo)
// clear chat messages on new server start
rc.ChatMessagesMutex.Lock()
rc.ChatMessages = []udp.Chat{}
rc.ChatMessagesMutex.Unlock()
_, err := rc.broadcaster.Send(version)
return err
}
// OnCarUpdate occurs every udp.RealTimePosInterval and returns car position, speed, etc.
// drivers top speeds are recorded per lap, as well as their last seen updated.
func (rc *RaceControl) OnCarUpdate(update udp.CarUpdate) error {
if ch, ok := rc.carUpdaters[update.CarID]; !ok || ch == nil {
rc.carUpdaters[update.CarID] = make(chan udp.CarUpdate, 1000)
go panicCapture(func() {
for update := range rc.carUpdaters[update.CarID] {
err := rc.handleCarUpdate(update)
if err != nil {
logrus.WithError(err).Error("Could not handle car update")
}
}
})
}
rc.carUpdaters[update.CarID] <- update
return nil
}
func (rc *RaceControl) handleCarUpdate(update udp.CarUpdate) error {
driver, err := rc.findConnectedDriverByCarID(update.CarID)
if err != nil {
return err
}
driver.mutex.Lock()
defer driver.mutex.Unlock()
speed := metersPerSecondToKilometersPerHour(
math.Sqrt(math.Pow(float64(update.Velocity.X), 2) + math.Pow(float64(update.Velocity.Z), 2)),
)
if speed > driver.CurrentCar().TopSpeedThisLap {
driver.CurrentCar().TopSpeedThisLap = speed
}
driver.LastSeen = time.Now()
driver.LastPos = update.Pos
_, err = rc.broadcaster.Send(update)
return err
}
var emptyCarInfoMutex = sync.Mutex{}
// OnNewSession occurs every new session. If the session is the first in an event and it is not a looped practice,
// then all driver information is cleared.
func (rc *RaceControl) OnNewSession(sessionInfo udp.SessionInfo) error {
oldSessionInfo := rc.SessionInfo
rc.SessionInfo = sessionInfo
rc.SessionStartTime = time.Now()
emptyCarInfo := true
rc.driverSwapPenaltiesMutex.Lock()
rc.driverSwapPenalties = make(map[udp.DriverGUID]*driverSwapPenalty)
rc.driverSwapPenaltiesMutex.Unlock()
if (rc.ConnectedDrivers.Len() > 0 || rc.DisconnectedDrivers.Len() > 0) && sessionInfo.Type == udp.SessionTypePractice {
if oldSessionInfo.Type == sessionInfo.Type && oldSessionInfo.Track == sessionInfo.Track && oldSessionInfo.TrackConfig == sessionInfo.TrackConfig && oldSessionInfo.Name == sessionInfo.Name {
// this is a looped event, keep the cars
emptyCarInfo = false
}
}
if emptyCarInfo {
_ = rc.ConnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
emptyCarInfoMutex.Lock()
defer emptyCarInfoMutex.Unlock()
*driver = *NewRaceControlDriver(driver.CarInfo)
return nil
})
// all disconnected drivers are removed when car info is emptied, otherwise we are just showing empty entries in
// the disconnected drivers table, which is pointless.
rc.DisconnectedDrivers = NewDriverMap(DisconnectedDrivers, rc.SortDrivers)
}
// clear out last lap completed time each new session
_ = rc.ConnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
driver.mutex.Lock()
defer driver.mutex.Unlock()
driver.CurrentCar().LastLapCompletedTime = time.Now()
return nil
})
var err error
trackInfo, err := rc.trackDataGateway.TrackInfo(sessionInfo.Track, sessionInfo.TrackConfig)
if err != nil {
return err
}
rc.TrackInfo = *trackInfo
trackMapData, err := rc.trackDataGateway.TrackMap(sessionInfo.Track, sessionInfo.TrackConfig)
if err != nil {
logrus.WithError(err).Errorf("Could not load track map data")
} else {
rc.TrackMapData = *trackMapData
}
logrus.Debugf("New session detected: %s at %s (%s) [emptyCarInfo: %t]", sessionInfo.Type.String(), sessionInfo.Track, sessionInfo.TrackConfig, emptyCarInfo)
// look for live timings stored previously
persistedInfo, err := rc.store.LoadLiveTimingsData()
if err == nil && persistedInfo != nil {
if persistedInfo.SessionType == rc.SessionInfo.Type &&
persistedInfo.Track == rc.SessionInfo.Track &&
persistedInfo.TrackLayout == rc.SessionInfo.TrackConfig &&
persistedInfo.SessionName == rc.SessionInfo.Name {
for guid, driver := range persistedInfo.Drivers {
_, driverPresentInDisconnectedList := rc.DisconnectedDrivers.Get(guid)
_, driverPresentInConnectedList := rc.ConnectedDrivers.Get(guid)
if !driverPresentInConnectedList && !driverPresentInDisconnectedList {
rc.DisconnectedDrivers.Add(guid, driver)
}
}
logrus.Infof("Loaded previous Live Timings data for %s (%s), num drivers: %d", persistedInfo.Track, persistedInfo.TrackLayout, len(persistedInfo.Drivers))
}
} else {
logrus.WithError(err).Debugf("Could not load persisted live timings practice data")
}
_, err = rc.broadcaster.Send(sessionInfo)
return err
}
// clearAllDrivers removes all known information about connected and disconnected drivers from RaceControl
func (rc *RaceControl) clearAllDrivers() {
rc.ConnectedDrivers = NewDriverMap(ConnectedDrivers, rc.SortDrivers)
rc.DisconnectedDrivers = NewDriverMap(DisconnectedDrivers, rc.SortDrivers)
rc.carIDToGUIDMutex.Lock()
rc.CarIDToGUID = make(map[udp.CarID]udp.DriverGUID)
rc.carIDToGUIDMutex.Unlock()
}
var sessionInfoRequestInterval = time.Second * 30
// requestSessionInfo sends a request every sessionInfoRequestInterval to get information about temps, etc in the session.
func (rc *RaceControl) requestSessionInfo() {
sessionInfoTicker := time.NewTicker(sessionInfoRequestInterval)
for {
select {
case <-sessionInfoTicker.C:
err := rc.process.SendUDPMessage(udp.GetSessionInfo{})
if err == ErrNoOpenUDPConnection {
logrus.WithError(err).Warnf("Couldn't send session info udp request. Breaking loop.")
sessionInfoTicker.Stop()
return
} else if err != nil {
logrus.WithError(err).Errorf("Couldn't send session info udp request")
}
case <-rc.serverProcessStopped:
logrus.Debugf("Assetto Process completed. Disconnecting all connected drivers. Session done.")
sessionInfoTicker.Stop()
var drivers []*RaceControlDriver
rc.persistTimingData()
// the server has just stopped. send disconnect messages for all connected cars.
_ = rc.ConnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
// Each takes a read lock, so we cannot call disconnectDriver (which takes a write lock) from inside it.
// we must instead append them to a slice and disconnect them outside the Each call.
drivers = append(drivers, driver)
return nil
})
for _, driver := range drivers {
// disconnect the driver
err := rc.disconnectDriver(driver)
if err != nil {
logrus.WithError(err).Errorf("Could not disconnect driver: %s (%s)", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID)
continue
}
}
if _, err := rc.broadcaster.Send(rc); err != nil {
logrus.WithError(err).Errorf("Couldn't broadcast race control")
}
return
}
}
}
func (rc *RaceControl) disconnectDriver(driver *RaceControlDriver) error {
driver.mutex.Lock()
carInfo := driver.CarInfo
carInfo.EventType = udp.EventConnectionClosed
driver.mutex.Unlock()
return rc.OnClientDisconnect(carInfo)
}
// OnSessionUpdate is called every sessionRequestInterval.
func (rc *RaceControl) OnSessionUpdate(sessionInfo udp.SessionInfo) (bool, error) {
oldSessionInfo := rc.SessionInfo
// we can't just copy over the session information, we must copy individual
// parts of it, as the session type is incorrect.
rc.SessionInfo.AmbientTemp = sessionInfo.AmbientTemp
rc.SessionInfo.RoadTemp = sessionInfo.RoadTemp
rc.SessionInfo.WeatherGraphics = sessionInfo.WeatherGraphics
rc.SessionInfo.ElapsedMilliseconds = sessionInfo.ElapsedMilliseconds
sessionHasChanged := oldSessionInfo.AmbientTemp != rc.SessionInfo.AmbientTemp || oldSessionInfo.RoadTemp != rc.SessionInfo.RoadTemp || oldSessionInfo.WeatherGraphics != rc.SessionInfo.WeatherGraphics
return sessionHasChanged, nil
}
// OnEndSession is called at the end of every session.
func (rc *RaceControl) OnEndSession(sessionFile udp.EndSession) error {
filename := filepath.Base(string(sessionFile))
logrus.Infof("End Session, file outputted at: %s", filename)
config := rc.process.Event().GetRaceConfig()
if config.DriverSwapEnabled == 1 {
_ = rc.ConnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
if driver.driverSwapCfn != nil {
logrus.Infof("Cancelling active driver swap for driver: %s. Reason: Session ended", driver.CarInfo.DriverGUID)
driver.driverSwapCfn()
}
return nil
})
_ = rc.DisconnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
if driver.driverSwapCfn != nil {
logrus.Infof("Cancelling active driver swap for driver: %s. Reason: Session ended", driver.CarInfo.DriverGUID)
driver.driverSwapCfn()
}
return nil
})
rc.driverSwapPenaltiesMutex.Lock()
defer rc.driverSwapPenaltiesMutex.Unlock()
if config.DriverSwapMinimumNumberOfSwaps > 0 {
results, err := LoadResult(filename, LoadResultWithoutPluginFire)
if err != nil {
logrus.WithError(err).Errorf("Could not load results file to check min driver swaps")
} else {
for _, result := range results.Result {
numSwaps := results.NumberOfDriverSwaps(result.CarID)
if numSwaps < config.DriverSwapMinimumNumberOfSwaps {
guid := udp.DriverGUID(result.DriverGUID)
penaltyTime := time.Duration((config.DriverSwapMinimumNumberOfSwaps-numSwaps)*config.DriverSwapNotEnoughSwapsPenalty) * time.Second
if _, ok := rc.driverSwapPenalties[guid]; ok {
rc.driverSwapPenalties[guid].penalty += penaltyTime
} else {
rc.driverSwapPenalties[guid] = &driverSwapPenalty{
carModel: result.CarModel,
penalty: penaltyTime,
}
}
}
}
}
}
for guid, penalty := range rc.driverSwapPenalties {
err := rc.penaltiesManager.applyPenalty(filename, string(guid), penalty.carModel, penalty.penalty.Seconds(), true)
if err != nil {
logrus.WithError(err).Errorf("could not apply driver swap penalty of %s to driver %s", penalty.penalty.String(), guid)
continue
}
}
}
if rc.currentTimeAttackEvent != nil && Premium() {
filename := filepath.Base(string(sessionFile))
err := rc.addFileToTimeAttackEvent(filename)
if err != nil {
return err
}
logrus.Infof("Time Attack Event (%s) Finished, results files have been combined and saved as %s", rc.currentTimeAttackEvent.EventName(), filename)
}
return nil
}
const timeAttackSuffix = "-time-attack"
func (rc *RaceControl) addFileToTimeAttackEvent(file string) error {
logrus.Info("Time Attack event completed, combining with any previous results")
results, err := LoadResult(file)
if err != nil {
logrus.WithError(err).Errorf("Could not read session results: %s", file)
return err
}
var resultsArray []*SessionResults
resultsArray = append(resultsArray, results)
if rc.currentTimeAttackEvent.TimeAttackCombinedResultFile != "" {
result, err := LoadResult(rc.currentTimeAttackEvent.TimeAttackCombinedResultFile + ".json")
if err != nil {
logrus.WithError(err).Errorf("Could not read session results: %s", file)
return err
}
resultsArray = append(resultsArray, result)
}
results = combineResults(resultsArray)
results.FallBackSort()
results.ClearKickedGUIDs()
results.NormaliseCarIDs()
if !strings.HasSuffix(results.SessionFile, timeAttackSuffix) {
results.SessionFile = results.SessionFile + timeAttackSuffix
}
results.Date = time.Now()
err = saveResults(results.SessionFile+".json", results)
if err != nil {
return err
}
rc.currentTimeAttackEvent.TimeAttackCombinedResultFile = results.SessionFile
return rc.store.UpsertCustomRace(rc.currentTimeAttackEvent)
}
// OnClientConnect stores CarID -> DriverGUID mappings. if a driver is known to have previously been in this event,
// they will be moved from DisconnectedDrivers to ConnectedDrivers.
func (rc *RaceControl) OnClientConnect(client udp.SessionCarInfo) error {
rc.carIDToGUIDMutex.Lock()
rc.CarIDToGUID[client.CarID] = client.DriverGUID
rc.carIDToGUIDMutex.Unlock()
client.DriverInitials = driverInitials(client.DriverName)
client.DriverName = driverName(client.DriverName)
client.CarName = prettifyName(client.CarModel, true)
var driver *RaceControlDriver
if disconnectedDriver, ok := rc.DisconnectedDrivers.Get(client.DriverGUID); ok {
driver = disconnectedDriver
logrus.Debugf("Driver %s (%s) reconnected in %s (car id: %d)", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID, driver.CarInfo.CarModel, client.CarID)
rc.DisconnectedDrivers.Del(client.DriverGUID)
} else {
if connectedDriver, ok := rc.ConnectedDrivers.Get(client.DriverGUID); ok {
driver = connectedDriver
logrus.Debugf("Driver %s (%s) reconnected (but was already connected...) in %s (car id: %d)", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID, driver.CarInfo.CarModel, client.CarID)
} else {
driver = NewRaceControlDriver(client)
logrus.Debugf("Driver %s (%s) connected in %s (car id: %d)", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID, driver.CarInfo.CarModel, client.CarID)
}
}
driver.mutex.Lock()
defer driver.mutex.Unlock()
driver.CarInfo = client
if _, ok := driver.Cars[driver.CarInfo.CarModel]; !ok {
driver.Cars[driver.CarInfo.CarModel] = NewRaceControlCarLapInfo(driver.CarInfo.CarModel)
}
driver.ConnectedTime = time.Now()
driver.LastSeen = time.Time{}
driver.CurrentCar().LastLapCompletedTime = time.Now()
rc.ConnectedDrivers.Add(driver.CarInfo.DriverGUID, driver)
_, err := rc.broadcaster.Send(client)
return err
}
// OnClientDisconnect moves a client from ConnectedDrivers to DisconnectedDrivers.
func (rc *RaceControl) OnClientDisconnect(client udp.SessionCarInfo) error {
if ch, ok := rc.carUpdaters[client.CarID]; ok && ch != nil {
delete(rc.carUpdaters, client.CarID)
}
driver, ok := rc.ConnectedDrivers.Get(client.DriverGUID)
if !ok {
return fmt.Errorf("racecontrol: client disconnected without ever being connected: %s (%s)", client.DriverName, client.DriverGUID)
}
driver.mutex.Lock()
defer driver.mutex.Unlock()
logrus.Debugf("Driver %s (%s) disconnected", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID)
driver.LoadedTime = time.Time{}
rc.ConnectedDrivers.Del(driver.CarInfo.DriverGUID)
if driver.TotalNumLaps > 0 {
rc.DisconnectedDrivers.Add(driver.CarInfo.DriverGUID, driver)
}
config := rc.process.Event().GetRaceConfig()
// if this race has driver swaps enabled we should initialise one now
if config.DriverSwapEnabled == 1 && rc.SessionInfo.Type.String() == SessionTypeRace.String() {
ticker := time.NewTicker(time.Second)
go rc.handleDriverSwap(ticker, config, client, driver)
}
_, err := rc.broadcaster.Send(client)
return err
}
type driverSwapPenalty struct {
penalty time.Duration
carModel string
}
func (rc *RaceControl) handleDriverSwap(ticker *time.Ticker, config CurrentRaceConfig, client udp.SessionCarInfo, driver *RaceControlDriver) {
var (
totalTime time.Duration
newDriverConnected bool
firstPositionUpdate bool
resumeSwap bool
)
completeTime := time.Second * time.Duration(config.DriverSwapMinTime)
initialGUID := client.DriverGUID
currentDriver := driver
position := currentDriver.LastPos
logrus.Infof(
"Driver: %s has initiated a driver swap, disconnected in position: %.2f, %.2f, %.2f. Next driver is expected to connect in the same position for a driver swap!",
currentDriver.CarInfo.DriverGUID,
currentDriver.LastPos.X,
currentDriver.LastPos.Y,
currentDriver.LastPos.Z,
)
driver.driverSwapContext, driver.driverSwapCfn = context.WithCancel(context.Background())
for {
select {
case <-driver.driverSwapContext.Done():
return
case <-ticker.C:
totalTime += time.Second
countdown := completeTime - totalTime
if !newDriverConnected {
reconnect := false
_ = rc.ConnectedDrivers.Each(func(driverGUID udp.DriverGUID, driver *RaceControlDriver) error {
if driver.CarInfo.CarID == currentDriver.CarInfo.CarID {
if driver.CarInfo.DriverGUID != currentDriver.CarInfo.DriverGUID {
if !driver.LoadedTime.IsZero() {
// new driver has connected in the same car
currentDriver = driver
newDriverConnected = true
logrus.Infof("Driver: %d (%s) has connected", currentDriver.CarInfo.CarID, currentDriver.CarInfo.DriverGUID)
}
} else {
// same driver reconnected
if resumeSwap {
logrus.Infof("Driver: %s has reconnected, driver swap still in progress", driver.CarInfo.DriverGUID)
currentDriver = driver
newDriverConnected = true
resumeSwap = false
} else {
logrus.Infof("Driver: %s has reconnected, driver swap aborted", initialGUID)
reconnect = true
}
}
}
return nil
})
if reconnect {
ticker.Stop()
return
}
} else {
if totalTime.Seconds() >= completeTime.Seconds() {
sendChat, err := udp.NewSendChat(currentDriver.CarInfo.CarID, "You are clear to leave the pits, go go go!")
if err == nil {
err := rc.process.SendUDPMessage(sendChat)
if err != nil {
logrus.WithError(err).Errorf("Unable to send driver swap clear to leave message to: %s", currentDriver.CarInfo.DriverName)
}
} else {
logrus.WithError(err).Errorf("Unable to build driver swap clear to leave message to: %s", currentDriver.CarInfo.DriverName)
}
logrus.Infof("Driver: %d has successfully completed their driver swap and is free to leave the pits", currentDriver.CarInfo.CarID)
ticker.Stop()
return
}
if !firstPositionUpdate {
nilVec := udp.Vec{X: 0, Y: 0, Z: 0}
if currentDriver.LastPos != nilVec {
sendChat, err := udp.NewSendChat(
currentDriver.CarInfo.CarID,
fmt.Sprintf(
"Hi! You are mid way through a driver swap, please wait %s before leaving the pits",
countdown.String(),
),
)
if err == nil {
err := rc.process.SendUDPMessage(sendChat)
if err != nil {
logrus.WithError(err).Errorf("Unable to send driver swap welcome message to: %s", currentDriver.CarInfo.DriverName)
}
} else {
logrus.WithError(err).Errorf("Unable to build driver swap welcome message to: %s", currentDriver.CarInfo.DriverName)
}
firstPositionUpdate = true
}
}
// if driver has moved
if rc.positionHasChanged(position, currentDriver.LastPos) && firstPositionUpdate {
// if the time is within the disqualify window
if countdown >= (time.Second * time.Duration(config.DriverSwapDisqualifyTime)) {
sendChat, err := udp.NewSendChat(
currentDriver.CarInfo.CarID,
fmt.Sprintf(
"You have been kicked from the session for leaving the pits %s early during a driver swap",
countdown.String(),
),
)
if err == nil {
err := rc.process.SendUDPMessage(sendChat)
if err != nil {
logrus.WithError(err).Errorf("Unable to send driver swap kicked message to: %s", currentDriver.CarInfo.DriverName)
}
} else {
logrus.WithError(err).Errorf("Unable to build driver swap kicked message to: %s", currentDriver.CarInfo.DriverName)
}
time.Sleep(5 * time.Second)
err = rc.process.SendUDPMessage(udp.NewKickUser(uint8(currentDriver.CarInfo.CarID)))
if err != nil {
logrus.WithError(err).Errorf("Unable to send kick command (driver swaps)")
} else {
logrus.Infof("Driver: %d has been kicked for leaving the pits %s early during a driver swap", currentDriver.CarInfo.CarID, countdown.String())
}
// don't stop the ticker, when the driver reconnects they should still have to wait
firstPositionUpdate = false
newDriverConnected = false
resumeSwap = true
currentDriver.LastPos = udp.Vec{X: 0, Y: 0, Z: 0}
} else if countdown >= (time.Second * time.Duration(config.DriverSwapPenaltyTime)) {
rc.driverSwapPenaltiesMutex.Lock()
{
if _, ok := rc.driverSwapPenalties[currentDriver.CarInfo.DriverGUID]; ok {
rc.driverSwapPenalties[currentDriver.CarInfo.DriverGUID].penalty += countdown + (time.Second * 5)
} else {
rc.driverSwapPenalties[currentDriver.CarInfo.DriverGUID] = &driverSwapPenalty{
penalty: countdown + (time.Second * 5),
carModel: currentDriver.CarInfo.CarModel,
}
}
}
rc.driverSwapPenaltiesMutex.Unlock()
sendChat, err := udp.NewSendChat(
currentDriver.CarInfo.CarID,
fmt.Sprintf(
"You have been given a %s second penalty for leaving the pits %s early during a driver swap",
(countdown+(time.Second*5)).String(),
countdown.String(),
),
)
if err == nil {
err := rc.process.SendUDPMessage(sendChat)
if err != nil {
logrus.WithError(err).Errorf("Unable to send driver swap penalty message to: %s", currentDriver.CarInfo.DriverName)
}
} else {
logrus.WithError(err).Errorf("Unable to build driver swap penalty message to: %s", currentDriver.CarInfo.DriverName)
}
logrus.Infof(
"Driver: %d has been given a %s second penalty for leaving the pits %s early during a driver swap",
currentDriver.CarInfo.CarID,
(countdown + (time.Second * 5)).String(),
countdown.String(),
)
ticker.Stop()
return
}
}
// send countdown messages
if firstPositionUpdate {
sendChat, err := udp.NewSendChat(currentDriver.CarInfo.CarID, fmt.Sprintf("Free to leave pits in %s", countdown.String()))
if err == nil {
err := rc.process.SendUDPMessage(sendChat)
if err != nil {
logrus.WithError(err).Errorf("Unable to send driver swap countdown message to: %s", currentDriver.CarInfo.DriverName)
}
} else {
logrus.WithError(err).Errorf("Unable to build driver swap countdown message to: %s", currentDriver.CarInfo.DriverName)
}
}
}
}
}
}
const allowedDriverSwapPositionDifference = 10.0
func (rc *RaceControl) positionHasChanged(initialPosition, currentPosition udp.Vec) bool {
logrus.Debugf("initial position: %.2f, %.2f, %.2f", initialPosition.X, initialPosition.Y, initialPosition.Z)
logrus.Debugf("current position: %.2f, %.2f, %.2f", currentPosition.X, currentPosition.Y, currentPosition.Z)
return math.Abs(float64(initialPosition.X-currentPosition.X)) >= allowedDriverSwapPositionDifference ||
math.Abs(float64(initialPosition.Y-currentPosition.Y)) >= allowedDriverSwapPositionDifference ||
math.Abs(float64(initialPosition.Z-currentPosition.Z)) >= allowedDriverSwapPositionDifference
}
// findConnectedDriverByCarID looks for a driver in ConnectedDrivers by their CarID. This is the only place CarID
// is used for a look-up, and it uses the CarIDToGUID map to perform the lookup.
func (rc *RaceControl) findConnectedDriverByCarID(carID udp.CarID) (*RaceControlDriver, error) {
rc.carIDToGUIDMutex.RLock()
driverGUID, ok := rc.CarIDToGUID[carID]
rc.carIDToGUIDMutex.RUnlock()
if !ok {
return nil, fmt.Errorf("racecontrol: could not find DriverGUID for CarID: %d", carID)
}
driver, ok := rc.ConnectedDrivers.Get(driverGUID)
if !ok {
return nil, fmt.Errorf("racecontrol: could not find connected driver for DriverGUID: %s", driverGUID)
}
return driver, nil
}
// OnClientLoaded marks a connected client as having loaded in.
func (rc *RaceControl) OnClientLoaded(loadedCar udp.ClientLoaded) error {
driver, err := rc.findConnectedDriverByCarID(udp.CarID(loadedCar))
if err != nil {
return err
}
serverConfig, err := rc.store.LoadServerOptions()
if err != nil {
return err
}
solWarning := ""
liveLink := ""
if rc.process.Event().GetRaceConfig().IsSol == 1 {
solWarning = "This server is running Sol. For the best experience please install Sol, and remember the other drivers may be driving in night conditions."
}
if config != nil && config.HTTP.BaseURL != "" {
liveLink = fmt.Sprintf("You can view live timings for this event at %s", config.HTTP.BaseURL+"/live-timing")
}
wrapped := strings.Split(wordwrap.WrapString(
fmt.Sprintf(
"Hi, %s! Welcome to the %s server! %s %s Make this race count! %s\n",
driver.CarInfo.DriverName,
serverConfig.GetName(),
serverConfig.ServerJoinMessage,
solWarning,
liveLink,
),
60,
), "\n")
for _, msg := range wrapped {
welcomeMessage, err := udp.NewSendChat(driver.CarInfo.CarID, msg)
if err == nil {
err := rc.process.SendUDPMessage(welcomeMessage)
if err != nil {
logrus.WithError(err).Errorf("Unable to send welcome message to: %s", driver.CarInfo.DriverName)
}
} else {
logrus.WithError(err).Errorf("Unable to build welcome message to: %s", driver.CarInfo.DriverName)
}
}
if err := rc.sendChampionshipPlayerSummaryMessage(driver); err != nil {
logrus.WithError(err).Errorf("Couldn't send championship welcome message to driver: %s", driver.CarInfo.DriverName)
}
logrus.Debugf("Driver: %s (%s) loaded", driver.CarInfo.DriverName, driver.CarInfo.DriverGUID)