mirror of
https://github.com/giongto35/cloud-game.git
synced 2026-07-18 17:16:04 +00:00
This PR contains refactored code.
**Changelog**
- Added new net code (the communication architecture was left intact).
- All network client IDs now have custom type `network.Uid` backed by github.com/rs/xid lib.
```
The string representation of a UUID takes 32 bytes, and the new type will take just 16.
Because of Golang JSON serialization problems with omitting zero-length empty slices (it can't)
and the need to use UID values as map keys (maps don't support slices as keys),
IDs are stored as strings (for now).
```
- A whole new WebSocket client/server implementation was added, as well as a new communication layer with synchronous and async call handlers.
- WebSocket connections now support dedicated Ping/Pong frames as opposed to original ping text messages.
- Used Gorilla WebSocket library doesn't allow concurrent (simultaneous) reads and writes, so this part was handled via send channel synchronization.
- New API structures can be found in the `pkg/api` folder.
- New communication protocol can be found in the `pkg/com/*` folder.
- Updated communication protocol is based on JSON-encoded messaging through WebSocket and has the following structure:
```
Packet
[id] string — a globally unique identification tag for the packet to track it trough a chain of requests.
t uint8 — contains packet type information (i.e. INIT_PACKET, SDP_OFFER_PACKET, ...).
[p] any — contains packet data (any type).
Each packet is a text message in JSON-serialized form (WebSocket control frames obviously not).
```
```
The main principle of this protocol and the duplex data exchange is:
the one who initializes connection is called a client, and
the one who is being connected to is called a server.
With the current architecture, the coordinator is the server, the user browsers and workers are the clients.
____ ____
↓ ↑ ↑ ↓
browser ⟶ coordinator ⟵ worker
(c) (s) (c)
One of the most crucial performance vise parts of these interactions is that
all the server-initiated calls to clients should be asynchronous!
```
- In order to track synchronous calls (packets) with an asynchronous protocol, such as WebSocket, each packet may have an `id` that should be copied in all subsequent requests/responses.
- The old `sessionID` param was replaced by `id` that should be stored inside the `p` (payload) part of the packet.
- It is possible to skip the default ping check for all connected workers on every user connection and just pick the first available with the new roundRobin param in the coordinator config file `coordinator.roundRobin: true/false`.
- Added a dedicated package for the system API (pkg/api/*).
- Added structured logging system (zerolog) for better logging and cloud services integration.
- Added a visual representation of the network message exchange in logs:
```
...
01:00:01.1078 3f98 INF w → c Handshake ws://localhost:8000/wso
01:00:01.1138 994 INF c ← w Handshake localhost:8000
01:00:01.1148 994 INF c ← w Connect cid=cep.hrg
01:00:01.1158 994 DBG c connection id has been changed to cepl7obdrc3jv66kp2ug cid=cep.hrg
01:00:01.1158 3f98 INF w → c Connect cid=cep.2ug
01:00:01.1158 994 INF c New worker / addr: localhost, ...
01:00:01.1158 3f98 INF w Connected to the coordinator localhost:8000 cid=cep.2ug
01:00:02.5834 994 INF c ← u Handshake localhost:8000
01:00:02.6175 994 INF c ← u Connect cid=cep.hs0
01:00:02.6209 994 INF c Search available workers cid=cep.hs0
01:00:02.6214 994 INF c Found next free worker cid=cep.hs0
01:00:02.6220 994 INF c → u InitSession cid=cep.hs0
01:00:02.6527 994 INF c ← u WebrtcInit cid=cep.hs0
01:00:02.6527 994 INF c → w ᵇWebrtcInit cid=cep.hrg
01:00:02.6537 3f98 INF w ← c WebrtcInit cid=cep.2ug
01:00:02.6537 3f98 INF w WebRTC start cid=cep.2ug
...
```
- Replaced a monstrous Prometheus metrics lib.
- Removed spflag dependency.
- Added new `version` config file param/constant for compatibility reasons.
- Bump the minimum required version for Go to 1.18 due to use of generics.
- Opus encoder now is cached and the default config is 96Kbps, complexity 5 (was 196Kbps, 8).
- Changed the default x264 quality parameters to `crf 23 / superfast / baseline` instead of `crf 17 / veryfast / main`.
- Added a separate WebRTC logging config param `webrtc.logLevel`.
- Worker now allocates much less memory.
- Optimized and fixed RGB to YUV converter.
- `--v=5` logging cmd flag was removed and replaced with the `debug` config parameter.
**Breaking changes (migration to v3)**
- Coordinator server API changes, see web/js/api/api.js.
- Coordinator client event API changes:
- c `GAME_PLAYER_IDX_CHANGE` (string) -> `GAME_PLAYER_IDX` (number)
- c `GAME_PLAYER_IDX` -> `GAME_PLAYER_IDX_SET`
- c `MEDIA_STREAM_INITIALIZED` -> `WEBRTC_NEW_CONNECTION`
- c `MEDIA_STREAM_SDP_AVAILABLE` -> `WEBRTC_SDP_OFFER`
- c `MEDIA_STREAM_CANDIDATE_ADD` -> `WEBRTC_ICE_CANDIDATE_RECEIVED`
- c `MEDIA_STREAM_CANDIDATE_FLUSH` -> `WEBRTC_ICE_CANDIDATES_FLUSH`
- x `MEDIA_STREAM_READY` -> **removed**
- c `CONNECTION_READY` -> `WEBRTC_CONNECTION_READY`
- c `CONNECTION_CLOSED` -> `WEBRTC_CONNECTION_CLOSED`
- c `GET_SERVER_LIST` -> `WORKER_LIST_FETCHED`
- x `KEY_STATE_UPDATED` -> **removed**
- n `WEBRTC_ICE_CANDIDATE_FOUND`
- n `WEBRTC_SDP_ANSWER`
- n `MESSAGE`
- `rtcp` module renamed to `webrtc`.
- Controller state equals Libretro controller state (changed order of bits), see: web/js/input/input.js.
- Added new `coordintaor.selector` config param that changes the selection algorithm for workers. By default it will select any free worker. Set this param to `ping` for the old behavior.
- Changed the name of the `webrtc.iceServers.url` config param to `webrtc.iceServers.urls`.
306 lines
10 KiB
JavaScript
306 lines
10 KiB
JavaScript
/**
|
|
* Touch controls.
|
|
*
|
|
* Virtual Gamepad / Joystick
|
|
* Left panel - Dpad
|
|
*
|
|
* @link https://jsfiddle.net/aa0et7tr/5/
|
|
* @version 1
|
|
*/
|
|
const touch = (() => {
|
|
const MAX_DIFF = 20; // radius of circle boundary
|
|
|
|
// vpad state, use for mouse button down
|
|
let vpadState = {[KEY.UP]: false, [KEY.DOWN]: false, [KEY.LEFT]: false, [KEY.RIGHT]: false};
|
|
let analogState = [0, 0];
|
|
|
|
let vpadTouchIdx = null;
|
|
let vpadTouchDrag = null;
|
|
let vpadHolder = document.getElementById('circle-pad-holder');
|
|
let vpadCircle = document.getElementById('circle-pad');
|
|
|
|
const buttons = Array.from(document.getElementsByClassName('btn'));
|
|
const playerSlider = document.getElementById('playeridx');
|
|
const dpad = Array.from(document.getElementsByClassName('dpad'));
|
|
|
|
const dpadToggle = document.getElementById('dpad-toggle')
|
|
dpadToggle.addEventListener('change', (e) => {
|
|
event.pub(DPAD_TOGGLE, {checked: e.target.checked});
|
|
});
|
|
|
|
let dpadMode = true;
|
|
const deadZone = 0.1;
|
|
|
|
function onDpadToggle(checked) {
|
|
if (dpadMode === checked) {
|
|
return //error?
|
|
}
|
|
if (dpadMode) {
|
|
dpadMode = false;
|
|
vpadHolder.classList.add('dpad-empty');
|
|
vpadCircle.classList.add('bong-full');
|
|
// reset dpad keys pressed before moving to analog stick mode
|
|
resetVpadState()
|
|
} else {
|
|
dpadMode = true;
|
|
vpadHolder.classList.remove('dpad-empty');
|
|
vpadCircle.classList.remove('bong-full');
|
|
}
|
|
}
|
|
|
|
function resetVpadState() {
|
|
if (dpadMode) {
|
|
// trigger up event?
|
|
checkVpadState(KEY.UP, false);
|
|
checkVpadState(KEY.DOWN, false);
|
|
checkVpadState(KEY.LEFT, false);
|
|
checkVpadState(KEY.RIGHT, false);
|
|
} else {
|
|
checkAnalogState(0, 0);
|
|
checkAnalogState(1, 0);
|
|
}
|
|
|
|
vpadTouchDrag = null;
|
|
vpadTouchIdx = null;
|
|
|
|
dpad.forEach(arrow => arrow.classList.remove('pressed'));
|
|
}
|
|
|
|
function checkVpadState(axis, state) {
|
|
if (state !== vpadState[axis]) {
|
|
vpadState[axis] = state;
|
|
event.pub(state ? KEY_PRESSED : KEY_RELEASED, {key: axis});
|
|
}
|
|
}
|
|
|
|
function checkAnalogState(axis, value) {
|
|
if (-deadZone < value && value < deadZone) value = 0;
|
|
if (analogState[axis] !== value) {
|
|
analogState[axis] = value;
|
|
event.pub(AXIS_CHANGED, {id: axis, value: value});
|
|
}
|
|
}
|
|
|
|
function handleVpadJoystickDown(event) {
|
|
vpadCircle.style['transition'] = '0s';
|
|
|
|
if (event.changedTouches) {
|
|
resetVpadState();
|
|
vpadTouchIdx = event.changedTouches[0].identifier;
|
|
event.clientX = event.changedTouches[0].clientX;
|
|
event.clientY = event.changedTouches[0].clientY;
|
|
}
|
|
|
|
vpadTouchDrag = {x: event.clientX, y: event.clientY};
|
|
}
|
|
|
|
function handleVpadJoystickUp() {
|
|
if (vpadTouchDrag === null) return;
|
|
|
|
vpadCircle.style['transition'] = '.2s';
|
|
vpadCircle.style['transform'] = 'translate3d(0px, 0px, 0px)';
|
|
|
|
resetVpadState();
|
|
}
|
|
|
|
function handleVpadJoystickMove(event) {
|
|
if (vpadTouchDrag === null) return;
|
|
|
|
if (event.changedTouches) {
|
|
// check if moving source is from other touch?
|
|
for (let i = 0; i < event.changedTouches.length; i++) {
|
|
if (event.changedTouches[i].identifier === vpadTouchIdx) {
|
|
event.clientX = event.changedTouches[i].clientX;
|
|
event.clientY = event.changedTouches[i].clientY;
|
|
}
|
|
}
|
|
if (event.clientX === undefined || event.clientY === undefined)
|
|
return;
|
|
}
|
|
|
|
let xDiff = event.clientX - vpadTouchDrag.x;
|
|
let yDiff = event.clientY - vpadTouchDrag.y;
|
|
let angle = Math.atan2(yDiff, xDiff);
|
|
let distance = Math.min(MAX_DIFF, Math.hypot(xDiff, yDiff));
|
|
let xNew = distance * Math.cos(angle);
|
|
let yNew = distance * Math.sin(angle);
|
|
|
|
if (env.display().isLayoutSwitched) {
|
|
let tmp = xNew;
|
|
xNew = yNew;
|
|
yNew = -tmp;
|
|
}
|
|
|
|
vpadCircle.style['transform'] = `translate(${xNew}px, ${yNew}px)`;
|
|
|
|
let xRatio = xNew / MAX_DIFF;
|
|
let yRatio = yNew / MAX_DIFF;
|
|
|
|
if (dpadMode) {
|
|
checkVpadState(KEY.LEFT, xRatio <= -0.5);
|
|
checkVpadState(KEY.RIGHT, xRatio >= 0.5);
|
|
checkVpadState(KEY.UP, yRatio <= -0.5);
|
|
checkVpadState(KEY.DOWN, yRatio >= 0.5);
|
|
} else {
|
|
checkAnalogState(0, xRatio);
|
|
checkAnalogState(1, yRatio);
|
|
}
|
|
}
|
|
|
|
// right side - control buttons
|
|
const _handleButton = (key, state) => checkVpadState(key, state)
|
|
|
|
function handleButtonDown() {
|
|
_handleButton(this.getAttribute('value'), true);
|
|
}
|
|
|
|
function handleButtonUp() {
|
|
_handleButton(this.getAttribute('value'), false);
|
|
}
|
|
|
|
function handleButtonClick() {
|
|
_handleButton(this.getAttribute('value'), true);
|
|
setTimeout(() => {
|
|
_handleButton(this.getAttribute('value'), false);
|
|
}, 30);
|
|
}
|
|
|
|
function handlePlayerSlider() {
|
|
event.pub(GAME_PLAYER_IDX, {index: this.value - 1});
|
|
}
|
|
|
|
// Touch menu
|
|
let menuTouchIdx = null;
|
|
let menuTouchDrag = null;
|
|
let menuTouchTime = null;
|
|
|
|
function handleMenuDown(event) {
|
|
// Identify of touch point
|
|
if (event.changedTouches) {
|
|
menuTouchIdx = event.changedTouches[0].identifier;
|
|
event.clientX = event.changedTouches[0].clientX;
|
|
event.clientY = event.changedTouches[0].clientY;
|
|
}
|
|
|
|
menuTouchDrag = {x: event.clientX, y: event.clientY,};
|
|
menuTouchTime = Date.now();
|
|
}
|
|
|
|
function handleMenuMove(evt) {
|
|
if (menuTouchDrag === null) return;
|
|
|
|
if (evt.changedTouches) {
|
|
// check if moving source is from other touch?
|
|
for (let i = 0; i < evt.changedTouches.length; i++) {
|
|
if (evt.changedTouches[i].identifier === menuTouchIdx) {
|
|
evt.clientX = evt.changedTouches[i].clientX;
|
|
evt.clientY = evt.changedTouches[i].clientY;
|
|
}
|
|
}
|
|
if (evt.clientX === undefined || evt.clientY === undefined)
|
|
return;
|
|
}
|
|
|
|
const pos = env.display().isLayoutSwitched ? evt.clientX - menuTouchDrag.x : menuTouchDrag.y - evt.clientY;
|
|
event.pub(MENU_PRESSED, pos);
|
|
}
|
|
|
|
function handleMenuUp(evt) {
|
|
if (menuTouchDrag === null) return;
|
|
if (evt.changedTouches) {
|
|
if (evt.changedTouches[0].identifier !== menuTouchIdx)
|
|
return;
|
|
evt.clientX = evt.changedTouches[0].clientX;
|
|
evt.clientY = evt.changedTouches[0].clientY;
|
|
}
|
|
|
|
let newY = env.display().isLayoutSwitched ? -menuTouchDrag.x + evt.clientX : menuTouchDrag.y - evt.clientY;
|
|
|
|
let interval = Date.now() - menuTouchTime; // 100ms?
|
|
if (interval < 200) {
|
|
// calc velo
|
|
newY = newY / interval * 250;
|
|
}
|
|
|
|
// current item?
|
|
event.pub(MENU_RELEASED, newY);
|
|
menuTouchDrag = null;
|
|
}
|
|
|
|
// Common events
|
|
function handleWindowMove(event) {
|
|
event.preventDefault();
|
|
handleVpadJoystickMove(event);
|
|
handleMenuMove(event);
|
|
|
|
// moving touch
|
|
if (event.changedTouches) {
|
|
for (let i = 0; i < event.changedTouches.length; i++) {
|
|
if (event.changedTouches[i].identifier !== menuTouchIdx && event.changedTouches[i].identifier !== vpadTouchIdx) {
|
|
// check class
|
|
|
|
let elem = document.elementFromPoint(event.changedTouches[i].clientX, event.changedTouches[i].clientY);
|
|
|
|
if (elem.classList.contains('btn')) {
|
|
elem.dispatchEvent(new Event('touchstart'));
|
|
} else {
|
|
elem.dispatchEvent(new Event('touchend'));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function handleWindowUp(ev) {
|
|
handleVpadJoystickUp(ev);
|
|
handleMenuUp(ev);
|
|
buttons.forEach((btn) => {
|
|
btn.dispatchEvent(new Event('touchend'));
|
|
});
|
|
}
|
|
|
|
// touch/mouse events for control buttons. mouseup events is binded to window.
|
|
buttons.forEach((btn) => {
|
|
btn.addEventListener('mousedown', handleButtonDown);
|
|
btn.addEventListener('touchstart', handleButtonDown, {passive: true});
|
|
btn.addEventListener('touchend', handleButtonUp);
|
|
});
|
|
|
|
// touch/mouse events for dpad. mouseup events is binded to window.
|
|
vpadHolder.addEventListener('mousedown', handleVpadJoystickDown);
|
|
vpadHolder.addEventListener('touchstart', handleVpadJoystickDown, {passive: true});
|
|
vpadHolder.addEventListener('touchend', handleVpadJoystickUp);
|
|
|
|
dpad.forEach((arrow) => {
|
|
arrow.addEventListener('click', handleButtonClick);
|
|
});
|
|
|
|
// touch/mouse events for player slider.
|
|
playerSlider.addEventListener('oninput', handlePlayerSlider);
|
|
playerSlider.addEventListener('onchange', handlePlayerSlider);
|
|
playerSlider.addEventListener('mouseup', handlePlayerSlider);
|
|
playerSlider.addEventListener('touchend', handlePlayerSlider);
|
|
|
|
// Bind events for menu
|
|
// TODO change this flow
|
|
event.pub(MENU_HANDLER_ATTACHED, {event: 'mousedown', handler: handleMenuDown});
|
|
event.pub(MENU_HANDLER_ATTACHED, {event: 'touchstart', handler: handleMenuDown});
|
|
event.pub(MENU_HANDLER_ATTACHED, {event: 'touchend', handler: handleMenuUp});
|
|
|
|
event.sub(DPAD_TOGGLE, (data) => onDpadToggle(data.checked));
|
|
|
|
return {
|
|
init: () => {
|
|
// add buttons into the state 🤦
|
|
Array.from(document.querySelectorAll('.btn,.btn-big')).forEach((el) => {
|
|
vpadState[el.getAttribute('value')] = false;
|
|
});
|
|
|
|
window.addEventListener('mousemove', handleWindowMove);
|
|
window.addEventListener('touchmove', handleWindowMove, {passive: false});
|
|
window.addEventListener('mouseup', handleWindowUp);
|
|
|
|
log.info('[input] touch input has been initialized');
|
|
}
|
|
}
|
|
})(document, event, KEY, window);
|