-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLinkUniversal.hpp
703 lines (614 loc) · 19.2 KB
/
LinkUniversal.hpp
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
#ifndef LINK_UNIVERSAL_H
#define LINK_UNIVERSAL_H
// --------------------------------------------------------------------------
// A multiplayer connection for the Link Cable and the Wireless Adapter.
// --------------------------------------------------------------------------
// Usage:
// - 1) Include this header in your main.cpp file and add:
// LinkUniversal* linkUniversal = new LinkUniversal();
// - 2) Add the required interrupt service routines: (*)
// irq_init(NULL);
// irq_add(II_VBLANK, LINK_UNIVERSAL_ISR_VBLANK);
// irq_add(II_SERIAL, LINK_UNIVERSAL_ISR_SERIAL);
// irq_add(II_TIMER3, LINK_UNIVERSAL_ISR_TIMER);
// - 3) Initialize the library with:
// linkUniversal->activate();
// - 4) Sync:
// linkUniversal->sync();
// // (put this line at the start of your game loop)
// - 5) Send/read messages by using:
// bool isConnected = linkUniversal->isConnected();
// u8 playerCount = linkUniversal->playerCount();
// u8 currentPlayerId = linkUniversal->currentPlayerId();
// linkUniversal->send(0x1234);
// if (isConnected && linkUniversal->canRead(!currentPlayerId)) {
// u16 message = linkUniversal->read(!currentPlayerId);
// // ...
// }
// --------------------------------------------------------------------------
// (*1) libtonc's interrupt handler sometimes ignores interrupts due to a bug.
// That causes packet loss. You REALLY want to use libugba's instead.
// (see examples)
// --------------------------------------------------------------------------
// (*2) For CABLE mode:
// The hardware is very sensitive to timing. Make sure that
// `LINK_CABLE_ISR_SERIAL()` is handled on time. That means:
// Be careful with DMA usage (which stops the CPU), and write short
// interrupt handlers (or activate nested interrupts by setting
// `REG_IME=1` at the start of your handlers).
// --------------------------------------------------------------------------
// `send(...)` restrictions:
// - 0xFFFF and 0x0 are reserved values, so don't use them!
// (they mean 'disconnected' and 'no data' respectively)
// --------------------------------------------------------------------------
#ifndef LINK_DEVELOPMENT
#pragma GCC system_header
#endif
#include "_link_common.hpp"
#include <cstdio>
#include "LinkCable.hpp"
#include "LinkWireless.hpp"
#ifndef LINK_UNIVERSAL_MAX_PLAYERS
/**
* @brief Maximum number of players. Default = 5
* \warning Keep in mind that LinkCable's limit is 4.
*/
#define LINK_UNIVERSAL_MAX_PLAYERS LINK_WIRELESS_MAX_PLAYERS
#endif
#ifndef LINK_UNIVERSAL_GAME_ID_FILTER
/**
* @brief Game ID Filter (`0x0000` ~ `0x7fff`). Default = 0 (no filter)
* This restricts wireless connections to rooms with a specific game ID.
* When disabled, it connects to any game ID and uses `0x7fff` when serving.
*/
#define LINK_UNIVERSAL_GAME_ID_FILTER 0
#endif
static volatile char LINK_UNIVERSAL_VERSION[] = "LinkUniversal/v7.0.3";
#define LINK_UNIVERSAL_DISCONNECTED LINK_CABLE_DISCONNECTED
#define LINK_UNIVERSAL_NO_DATA LINK_CABLE_NO_DATA
/**
* @brief A multiplayer connection for the Link Cable and the Wireless Adapter.
*/
class LinkUniversal {
private:
using u32 = unsigned int;
using u16 = unsigned short;
using u8 = unsigned char;
using s8 = signed char;
using U16Queue = Link::Queue<u16, LINK_CABLE_QUEUE_SIZE>;
static constexpr int MAX_ROOM_NUMBER = 32000;
static constexpr int INIT_WAIT_FRAMES = 10;
static constexpr int SWITCH_WAIT_FRAMES = 25;
static constexpr int SWITCH_WAIT_FRAMES_RANDOM = 10;
static constexpr int BROADCAST_SEARCH_WAIT_FRAMES = 10;
static constexpr int SERVE_WAIT_FRAMES = 60;
static constexpr int SERVE_WAIT_FRAMES_RANDOM = 30;
public:
enum State { INITIALIZING, WAITING, CONNECTED };
enum Mode { LINK_CABLE, LINK_WIRELESS };
enum Protocol {
AUTODETECT,
CABLE,
WIRELESS_AUTO,
WIRELESS_SERVER,
WIRELESS_CLIENT
};
struct CableOptions {
LinkCable::BaudRate baudRate;
u32 timeout;
u16 interval;
u8 sendTimerId;
};
struct WirelessOptions {
bool retransmission;
u32 maxPlayers;
u32 timeout;
u16 interval;
u8 sendTimerId;
};
/**
* @brief Constructs a new LinkUniversal object.
* @param protocol One of the enum values from `LinkUniversal::Protocol`.
* @param gameName The game name that will be broadcasted in wireless sessions
* (max `14` characters). The string must be a null-terminated character
* array. The library uses this to only connect to servers from the same game.
* @param cableOptions All the LinkCable constructor parameters in one struct.
* @param wirelessOptions All the LinkWireless constructor parameters in one
* struct.
* @param randomSeed Random seed used for waits to prevent livelocks. If you
* use _libtonc_, pass `__qran_seed`.
*/
explicit LinkUniversal(Protocol protocol = AUTODETECT,
const char* gameName = "",
CableOptions cableOptions =
CableOptions{LinkCable::BaudRate::BAUD_RATE_1,
LINK_CABLE_DEFAULT_TIMEOUT,
LINK_CABLE_DEFAULT_INTERVAL,
LINK_CABLE_DEFAULT_SEND_TIMER_ID},
WirelessOptions wirelessOptions =
WirelessOptions{
true, LINK_UNIVERSAL_MAX_PLAYERS,
LINK_WIRELESS_DEFAULT_TIMEOUT,
LINK_WIRELESS_DEFAULT_INTERVAL,
LINK_WIRELESS_DEFAULT_SEND_TIMER_ID},
int randomSeed = 123) {
this->linkCable =
new LinkCable(cableOptions.baudRate, cableOptions.timeout,
cableOptions.interval, cableOptions.sendTimerId);
this->linkWireless = new LinkWireless(
wirelessOptions.retransmission, true,
Link::_min(wirelessOptions.maxPlayers, LINK_UNIVERSAL_MAX_PLAYERS),
wirelessOptions.timeout, wirelessOptions.interval,
wirelessOptions.sendTimerId);
this->config.protocol = protocol;
this->config.gameName = gameName;
this->randomSeed = randomSeed;
}
/**
* @brief Returns whether the library is active or not.
*/
[[nodiscard]] bool isActive() { return isEnabled; }
/**
* @brief Activates the library.
*/
void activate() {
reset();
isEnabled = true;
}
/**
* @brief Deactivates the library.
*/
void deactivate() {
isEnabled = false;
linkCable->deactivate();
linkWireless->deactivate();
resetState();
}
/**
* @brief Returns `true` if there are at least 2 connected players.
*/
[[nodiscard]] bool isConnected() { return state == CONNECTED; }
/**
* @brief Returns the number of connected players (`0~5`).
*/
[[nodiscard]] u8 playerCount() {
return mode == LINK_CABLE ? linkCable->playerCount()
: linkWireless->playerCount();
}
/**
* @brief Returns the current player ID (`0~4`).
*/
[[nodiscard]] u8 currentPlayerId() {
return mode == LINK_CABLE ? linkCable->currentPlayerId()
: linkWireless->currentPlayerId();
}
/**
* @brief Call this method every time you need to fetch new data.
*/
void sync() {
if (!isEnabled)
return;
u16 keys = ~Link::_REG_KEYS & Link::_KEY_ANY;
randomSeed += keys;
randomSeed += Link::_REG_RCNT;
randomSeed += Link::_REG_SIOCNT;
if (mode == LINK_CABLE)
linkCable->sync();
switch (state) {
case INITIALIZING: {
waitCount++;
if (waitCount > INIT_WAIT_FRAMES)
start();
break;
};
case WAITING: {
if (mode == LINK_CABLE) {
// Cable, waiting...
if (isConnectedCable()) {
state = CONNECTED;
goto connected;
}
} else {
// Wireless, waiting...
if (isConnectedWireless()) {
state = CONNECTED;
goto connected;
} else {
if (!autoDiscoverWirelessConnections())
waitCount = switchWait;
if (isConnectedWireless())
goto connected;
}
}
waitCount++;
if (waitCount > switchWait)
toggleMode();
break;
}
case CONNECTED: {
connected:
if (mode == LINK_CABLE) {
// Cable, connected...
if (!isConnectedCable()) {
toggleMode();
break;
}
receiveCableMessages();
} else {
// Wireless, connected...
if (!isConnectedWireless()) {
toggleMode();
break;
}
receiveWirelessMessages();
}
break;
}
default: {
}
}
}
/**
* @brief Waits for data from player #`playerId`. Returns `true` on success,
* or `false` on disconnection.
* @param playerId A player ID.
*/
bool waitFor(u8 playerId) {
return waitFor(playerId, []() { return false; });
}
/**
* @brief Waits for data from player #`playerId`. Returns `true` on success,
* or `false` on disconnection.
* @param playerId ID of player to wait data from.
* @param cancel A function that will be continuously invoked. If it returns
* `true`, the wait be aborted.
*/
template <typename F>
bool waitFor(u8 playerId, F cancel) {
sync();
u8 timerId = mode == LINK_CABLE ? linkCable->config.sendTimerId
: linkWireless->config.sendTimerId;
while (isConnected() && !canRead(playerId) && !cancel()) {
Link::_IntrWait(1, Link::_IRQ_SERIAL | Link::_TIMER_IRQ_IDS[timerId]);
sync();
}
return isConnected() && canRead(playerId);
}
/**
* @brief Returns `true` if there are pending messages from player
* #`playerId`.
* @param playerId A player ID.
* \warning Keep in mind that if this returns `false`, it will keep doing so
* until you *fetch new data* with `sync()`.
*/
[[nodiscard]] bool canRead(u8 playerId) {
return !incomingMessages[playerId].isEmpty();
}
/**
* @brief Dequeues and returns the next message from player #`playerId`.
* @param playerId A player ID.
* \warning If there's no data from that player, a `0` will be returned.
*/
u16 read(u8 playerId) { return incomingMessages[playerId].pop(); }
/**
* @brief Returns the next message from player #`playerId` without dequeuing
* it.
* @param playerId A player ID.
* \warning If there's no data from that player, a `0` will be returned.
*/
[[nodiscard]] u16 peek(u8 playerId) {
return incomingMessages[playerId].peek();
}
/**
* @brief Sends `data` to all connected players.
* If the buffers are full, it either drops the oldest message (on cable mode)
* or ignores it returning `false` (on wireless mode).
* @param data The value to be sent.
*/
bool send(u16 data) {
if (data == LINK_CABLE_DISCONNECTED || data == LINK_CABLE_NO_DATA)
return false;
if (mode == LINK_CABLE) {
linkCable->send(data);
return true;
} else {
return linkWireless->send(data);
}
}
/**
* @brief Returns the current state.
* @return One of the enum values from `LinkUniversal::State`.
*/
[[nodiscard]] State getState() { return state; }
/**
* @brief Returns the active mode.
* @return One of the enum values from `LinkUniversal::Mode`.
*/
[[nodiscard]] Mode getMode() { return mode; }
/**
* @brief Returns the active protocol
* @return One of the enum values from `LinkUniversal::Protocol`.
*/
[[nodiscard]] Protocol getProtocol() { return this->config.protocol; }
/**
* @brief Returns the wireless state (same as `LinkWireless::getState()`).
*/
[[nodiscard]] LinkWireless::State getWirelessState() {
return linkWireless->getState();
}
/**
* @brief Sets the active `protocol`.
* @param protocol One of the enum values from `LinkUniversal::Protocol`.
*/
void setProtocol(Protocol protocol) { this->config.protocol = protocol; }
~LinkUniversal() {
delete linkCable;
delete linkWireless;
}
/**
* @brief Returns the wait count.
* \warning This is internal API!
*/
[[nodiscard]] u32 _getWaitCount() { return waitCount; }
/**
* @brief Returns the sub-wait count.
* \warning This is internal API!
*/
[[nodiscard]] u32 _getSubWaitCount() { return subWaitCount; }
/**
* @brief This method is called by the VBLANK interrupt handler.
* \warning This is internal API!
*/
void _onVBlank() {
if (mode == LINK_CABLE)
linkCable->_onVBlank();
else
linkWireless->_onVBlank();
}
/**
* @brief This method is called by the SERIAL interrupt handler.
* \warning This is internal API!
*/
void _onSerial() {
if (mode == LINK_CABLE)
linkCable->_onSerial();
else
linkWireless->_onSerial();
}
/**
* @brief This method is called by the TIMER interrupt handler.
* \warning This is internal API!
*/
void _onTimer() {
if (mode == LINK_CABLE)
linkCable->_onTimer();
else
linkWireless->_onTimer();
}
LinkCable* linkCable;
LinkWireless* linkWireless;
private:
struct Config {
Protocol protocol;
const char* gameName;
};
U16Queue incomingMessages[LINK_UNIVERSAL_MAX_PLAYERS];
Config config;
State state = INITIALIZING;
Mode mode = LINK_CABLE;
u32 waitCount = 0;
u32 switchWait = 0;
u32 subWaitCount = 0;
u32 serveWait = 0;
int randomSeed = 0;
volatile bool isEnabled = false;
void receiveCableMessages() {
static constexpr u32 MAX_PLAYERS =
LINK_UNIVERSAL_MAX_PLAYERS < LINK_CABLE_MAX_PLAYERS
? LINK_UNIVERSAL_MAX_PLAYERS
: LINK_CABLE_MAX_PLAYERS;
for (u32 i = 0; i < MAX_PLAYERS; i++) {
while (linkCable->canRead(i))
incomingMessages[i].push(linkCable->read(i));
}
}
void receiveWirelessMessages() {
LinkWireless::Message messages[LINK_WIRELESS_QUEUE_SIZE];
linkWireless->receive(messages);
for (u32 i = 0; i < LINK_WIRELESS_QUEUE_SIZE; i++) {
auto message = messages[i];
if (message.packetId == LINK_WIRELESS_END)
break;
if (message.playerId < LINK_UNIVERSAL_MAX_PLAYERS)
incomingMessages[message.playerId].push(message.data);
}
}
bool autoDiscoverWirelessConnections() {
switch (linkWireless->getState()) {
case LinkWireless::State::NEEDS_RESET:
case LinkWireless::State::AUTHENTICATED: {
subWaitCount = 0;
linkWireless->getServersAsyncStart();
break;
}
case LinkWireless::State::SEARCHING: {
waitCount = 0;
subWaitCount++;
if (subWaitCount >= BROADCAST_SEARCH_WAIT_FRAMES) {
if (!tryConnectOrServeWirelessSession())
return false;
}
break;
}
case LinkWireless::State::CONNECTING: {
if (!linkWireless->keepConnecting())
return false;
break;
}
case LinkWireless::State::SERVING: {
waitCount = 0;
subWaitCount++;
if (subWaitCount > serveWait)
return false;
break;
}
case LinkWireless::State::CONNECTED: {
// (should not happen)
break;
}
default: {
}
}
return true;
}
bool tryConnectOrServeWirelessSession() {
LinkWireless::Server servers[LINK_WIRELESS_MAX_SERVERS];
if (!linkWireless->getServersAsyncEnd(servers))
return false;
u32 maxRandomNumber = 0;
u32 serverIndex = 0;
for (u32 i = 0; i < LINK_WIRELESS_MAX_SERVERS; i++) {
auto server = servers[i];
if (server.id == LINK_WIRELESS_END)
break;
if (!server.isFull() &&
std::strcmp(server.gameName, config.gameName) == 0 &&
(LINK_UNIVERSAL_GAME_ID_FILTER == 0 ||
server.gameId == LINK_UNIVERSAL_GAME_ID_FILTER)) {
u32 randomNumber = safeStoi(server.userName);
if (randomNumber > maxRandomNumber && randomNumber < MAX_ROOM_NUMBER) {
maxRandomNumber = randomNumber;
serverIndex = i;
}
}
}
if (maxRandomNumber > 0 && config.protocol != WIRELESS_SERVER) {
if (!linkWireless->connect(servers[serverIndex].id))
return false;
} else {
if (config.protocol == WIRELESS_CLIENT)
return false;
subWaitCount = 0;
serveWait = SERVE_WAIT_FRAMES + _qran_range(1, SERVE_WAIT_FRAMES_RANDOM);
u32 randomNumber = _qran_range(1, MAX_ROOM_NUMBER);
char randomNumberStr[6];
std::snprintf(randomNumberStr, sizeof(randomNumberStr), "%d",
randomNumber);
if (!linkWireless->serve(config.gameName, randomNumberStr,
LINK_UNIVERSAL_GAME_ID_FILTER > 0
? LINK_UNIVERSAL_GAME_ID_FILTER
: LINK_WIRELESS_MAX_GAME_ID))
return false;
}
return true;
}
bool isConnectedCable() { return linkCable->isConnected(); }
bool isConnectedWireless() { return linkWireless->isConnected(); }
void reset() {
switch (config.protocol) {
case AUTODETECT:
case CABLE: {
setMode(LINK_CABLE);
break;
}
case WIRELESS_AUTO:
case WIRELESS_SERVER:
case WIRELESS_CLIENT: {
setMode(LINK_WIRELESS);
break;
}
default: {
}
}
}
void stop() {
if (mode == LINK_CABLE)
linkCable->deactivate();
else
linkWireless->deactivate(false);
}
void toggleMode() {
switch (config.protocol) {
case AUTODETECT: {
setMode(mode == LINK_CABLE ? LINK_WIRELESS : LINK_CABLE);
break;
}
case CABLE: {
setMode(LINK_CABLE);
break;
}
case WIRELESS_AUTO:
case WIRELESS_SERVER:
case WIRELESS_CLIENT: {
setMode(LINK_WIRELESS);
break;
}
default: {
}
}
}
void setMode(Mode mode) {
stop();
this->state = INITIALIZING;
this->mode = mode;
resetState();
}
void start() {
if (mode == LINK_CABLE)
linkCable->activate();
else {
if (!linkWireless->activate()) {
toggleMode();
return;
}
}
state = WAITING;
resetState();
}
void resetState() {
waitCount = 0;
switchWait = SWITCH_WAIT_FRAMES + _qran_range(1, SWITCH_WAIT_FRAMES_RANDOM);
subWaitCount = 0;
serveWait = 0;
for (u32 i = 0; i < LINK_UNIVERSAL_MAX_PLAYERS; i++)
incomingMessages[i].clear();
}
u32 safeStoi(const char* str) {
u32 num = 0;
while (*str != '\0') {
char ch = *str;
if (ch < '0' || ch > '9')
return 0;
num = num * 10 + (ch - '0');
str++;
}
return num;
}
int _qran() {
randomSeed = 1664525 * randomSeed + 1013904223;
return (randomSeed >> 16) & 0x7FFF;
}
int _qran_range(int min, int max) {
return (_qran() * (max - min) >> 15) + min;
}
};
extern LinkUniversal* linkUniversal;
/**
* @brief VBLANK interrupt handler.
*/
inline void LINK_UNIVERSAL_ISR_VBLANK() {
linkUniversal->_onVBlank();
}
/**
* @brief SERIAL interrupt handler.
*/
inline void LINK_UNIVERSAL_ISR_SERIAL() {
linkUniversal->_onSerial();
}
/**
* @brief TIMER interrupt handler.
*/
inline void LINK_UNIVERSAL_ISR_TIMER() {
linkUniversal->_onTimer();
}
#endif // LINK_UNIVERSAL_H