1
0
mirror of https://git.ngram.ca/OpenJam/rc-servers synced 2026-08-23 23:08:52 +00:00

Add support for matchmaker sending clients off to game server

This commit is contained in:
NG (Graham)
2025-06-19 22:05:16 -04:00
parent 8cd63c3122
commit 9f74a2e76a
24 changed files with 543 additions and 45 deletions

View File

@@ -19,6 +19,10 @@ pub struct CliArgs {
#[arg(long, default_value_t = {"../data/robocraft".to_string()})]
pub data: String,
/// Domain and port of the game match server
#[arg(long, default_value_t = {"127.0.0.1:4542".to_string()})]
pub redirect: String,
/// Handle one connection and then exit
#[arg(short = '1', long)]
pub once: bool,

View File

@@ -0,0 +1 @@
pub mod network;

View File

@@ -0,0 +1,60 @@
#[derive(Clone)]
pub struct NetworkConfigData {
pub network_channel_ty: String,
pub max_sent_message_queue_size: u16,
pub is_acks_long: bool,
pub network_drop_threshold: u8,
pub packet_size: u16,
pub max_combined_reliable_message_count: u16,
pub max_combined_reliable_message_size: u16,
pub min_update_timeout: u16, // stored as a u32 for some reason
pub max_delay: i64,
pub overflow_threshold: u8,
pub max_packet_size: u16,
pub resend_delay_base: f64,
pub resend_delay_rtt_mult: f64,
pub network_peer_update_interval: i32,
pub max_delay_for_disconnect: i32, // milliseconds
}
impl NetworkConfigData {
pub fn as_transmissible<C>(&self) -> polariton::operation::Typed<C> {
polariton::operation::Typed::HashMap(vec![
(polariton::operation::Typed::Str("NetworkChannelTypes".into()), polariton::operation::Typed::Str(self.network_channel_ty.clone().into())),
(polariton::operation::Typed::Str("MaxSentMessageQueueSize".into()), polariton::operation::Typed::Long(self.max_sent_message_queue_size as _)),
(polariton::operation::Typed::Str("IsAcksLong".into()), polariton::operation::Typed::Long(self.is_acks_long as _)),
(polariton::operation::Typed::Str("NetworkDropThreshold".into()), polariton::operation::Typed::Long(self.network_drop_threshold as _)),
(polariton::operation::Typed::Str("PacketSize".into()), polariton::operation::Typed::Long(self.packet_size as _)),
(polariton::operation::Typed::Str("MaxCombinedReliableMessageCount".into()), polariton::operation::Typed::Long(self.max_combined_reliable_message_count as _)),
(polariton::operation::Typed::Str("MaxCombinedReliableMessageSize".into()), polariton::operation::Typed::Long(self.max_combined_reliable_message_size as _)),
(polariton::operation::Typed::Str("MinUpdateTimeout".into()), polariton::operation::Typed::Long(self.min_update_timeout as _)),
(polariton::operation::Typed::Str("MaxDelay".into()), polariton::operation::Typed::Long(self.max_delay)),
(polariton::operation::Typed::Str("OverflowThreshold".into()), polariton::operation::Typed::Long(self.overflow_threshold as _)),
(polariton::operation::Typed::Str("MaxPacketSize".into()), polariton::operation::Typed::Long(self.max_packet_size as _)),
(polariton::operation::Typed::Str("ResendDelayBase".into()), polariton::operation::Typed::Double(self.resend_delay_base)),
(polariton::operation::Typed::Str("ResendDelayRttMult".into()), polariton::operation::Typed::Double(self.resend_delay_rtt_mult)),
(polariton::operation::Typed::Str("NetworkPeerUpdateInterval".into()), polariton::operation::Typed::Long(self.network_peer_update_interval as _)),
(polariton::operation::Typed::Str("MaxMillisecondsDelayForBeingDisconnected".into()), polariton::operation::Typed::Long(self.max_delay_for_disconnect as _)),
].into())
}
pub fn from_conf(conf: oj_rc_core::persist::NetworkConf) -> Self {
Self {
network_channel_ty: conf.network_channel_ty,
max_sent_message_queue_size: conf.max_sent_message_queue_size,
is_acks_long: conf.is_acks_long,
network_drop_threshold: conf.network_drop_threshold,
packet_size: conf.packet_size,
max_combined_reliable_message_count: conf.max_combined_reliable_message_count,
max_combined_reliable_message_size: conf.max_combined_reliable_message_size,
min_update_timeout: conf.min_update_timeout,
max_delay: conf.max_delay,
overflow_threshold: conf.overflow_threshold,
max_packet_size: conf.max_packet_size,
resend_delay_base: conf.resend_delay_base,
resend_delay_rtt_mult: conf.resend_delay_rtt_mult,
network_peer_update_interval: conf.network_peer_update_interval,
max_delay_for_disconnect: conf.max_delay_for_disconnect_ms,
}
}
}

View File

@@ -0,0 +1,77 @@
const HOST_IP_PARAM_KEY: u8 = 6; // seems to actually be an IP address or domain name
const HOST_PORT_PARAM_KEY: u8 = 7;
const MAP_NAME_PARAM_KEY: u8 = 8;
const GAME_MODE_PARAM_KEY: u8 = 1;
const GAME_GUID_PARAM_KEY: u8 = 40;
const IS_RANKED_PARAM_KEY: u8 = 25;
const IS_CUSTOM_GAME_PARAM_KEY: u8 = 27;
const MAP_VISIBILITY_PARAM_KEY: u8 = 28;
const IS_AUTO_HEAL_PARAM_KEY: u8 = 42;
const PLAYER_DATA_PARAM_KEY: u8 = 5;
const NETWORK_CONFIG_PARAM_KEY: u8 = 23;
pub struct BattleEnter {
pub host: String,
pub port: u16,
pub map: String,
pub mode: oj_rc_core::data::game_mode::GameMode,
pub guid: String,
pub is_ranked: bool,
pub is_custom: bool,
pub visibility: Option<oj_rc_core::data::game_mode::MapVisibility>, // ?
pub auto_heal: bool,
pub player_datas: Vec<oj_rc_core::data::player_data::PlayerData>,
pub network_config: crate::data::network::NetworkConfigData,
}
impl BattleEnter {
const CODE: u8 = 5;
fn as_transmissible<C>(&self) -> Vec<(u8, polariton::operation::Typed<C>)> {
let player_datas = polariton::operation::Typed::Arr(polariton::operation::Arr {
ty: polariton::serdes::TypePrefix::HashMap,
items: self.player_datas.iter().map(|x| x.as_transmissible()).collect()
});
let mut vec = Vec::with_capacity(11);
vec.push((HOST_IP_PARAM_KEY, polariton::operation::Typed::Str(self.host.clone().into())));
vec.push((HOST_PORT_PARAM_KEY, polariton::operation::Typed::Int(self.port as _)));
vec.push((MAP_NAME_PARAM_KEY, polariton::operation::Typed::Str(self.map.clone().into())));
vec.push((GAME_MODE_PARAM_KEY, polariton::operation::Typed::Int(self.mode as i32)));
vec.push((GAME_GUID_PARAM_KEY, polariton::operation::Typed::Str(self.guid.clone().into())));
vec.push((IS_RANKED_PARAM_KEY, polariton::operation::Typed::Bool(self.is_ranked)));
vec.push((IS_CUSTOM_GAME_PARAM_KEY, polariton::operation::Typed::Bool(self.is_custom)));
if let Some(visibility) = self.visibility {
vec.push((MAP_VISIBILITY_PARAM_KEY, polariton::operation::Typed::Int(visibility as i32)));
}
vec.push((IS_AUTO_HEAL_PARAM_KEY, polariton::operation::Typed::Bool(self.auto_heal)));
vec.push((PLAYER_DATA_PARAM_KEY, player_datas));
vec.push((NETWORK_CONFIG_PARAM_KEY, self.network_config.as_transmissible()));
vec
}
}
impl <C: Send + 'static> polariton_server::events::IntoEvent<C> for BattleEnter {
const CHANNEL: u8 = 0;
const ENCRYPT: bool = true;
const RELIABLE: bool = true;
fn into_event(self) -> polariton::operation::Event<C> {
polariton::operation::Event {
code: Self::CODE,
params: self.as_transmissible().into(),
}
}
}
impl <C: Send + 'static> polariton_server::events::IntoEvent<C> for &BattleEnter {
const CHANNEL: u8 = 0;
const ENCRYPT: bool = true;
const RELIABLE: bool = true;
fn into_event(self) -> polariton::operation::Event<C> {
polariton::operation::Event {
code: BattleEnter::CODE,
params: self.as_transmissible().into(),
}
}
}

View File

@@ -0,0 +1,18 @@
pub struct BattleFound;
impl BattleFound {
const CODE: u8 = 3;
}
impl <C: Send + 'static> polariton_server::events::IntoEvent<C> for BattleFound {
const CHANNEL: u8 = 0;
const ENCRYPT: bool = true;
const RELIABLE: bool = true;
fn into_event(self) -> polariton::operation::Event<C> {
polariton::operation::Event {
code: Self::CODE,
params: polariton::operation::ParameterTable::with_capacity(0),
}
}
}

View File

@@ -0,0 +1,27 @@
const DATA_PARAM_KEY: u8 = 21;
const TEXT_PARAM_KEY: u8 = 22;
pub struct QueueJoinError {
pub code: i16,
pub text: String,
}
impl QueueJoinError {
const CODE: u8 = 1;
}
impl <C: Send + 'static> polariton_server::events::IntoEvent<C> for QueueJoinError {
const CHANNEL: u8 = 0;
const ENCRYPT: bool = true;
const RELIABLE: bool = true;
fn into_event(self) -> polariton::operation::Event<C> {
polariton::operation::Event {
code: Self::CODE,
params: vec![
(DATA_PARAM_KEY, polariton::operation::Typed::Short(self.code)),
(TEXT_PARAM_KEY, polariton::operation::Typed::Str(self.text.into())),
].into(),
}
}
}

View File

@@ -0,0 +1,3 @@
pub mod battle_found;
pub mod battle_enter;
pub mod enqueue_error;

110
rc_lobby_room/src/lobby.rs Normal file
View File

@@ -0,0 +1,110 @@
use std::{collections::HashMap, hash::Hash};
#[derive(Hash, Eq, PartialEq, Clone)]
struct QueueKey {
map: String,
mode: oj_rc_core::data::game_mode::GameMode,
visibility: oj_rc_core::data::game_mode::MapVisibility,
auto_heal: bool,
}
struct QueueUser {
emitter: polariton_server::events::EventEmitter,
player: oj_rc_core::data::player_data::PlayerData,
}
pub struct QueueHandler {
users_in_queue: std::sync::Mutex<HashMap<QueueKey, Vec<QueueUser>>>,
users_per_game: usize,
is_enabled: bool,
hostname: String,
hostport: u16,
network_conf: crate::data::network::NetworkConfigData,
}
impl QueueHandler {
pub fn new(conf: &oj_rc_core::ConfigImpl, game_host: &str) -> Self {
let (domain, port_str) = game_host.split_once(':').expect("Invalid redirect address (must be domain:port)");
Self {
users_in_queue: std::sync::Mutex::new(HashMap::new()),
users_per_game: oj_rc_core::ConfigProvider::<()>::players_per_game(conf),
is_enabled: oj_rc_core::ConfigProvider::<()>::is_multiplayer_enabled(conf),
hostname: domain.to_owned(),
hostport: port_str.parse().expect("Invalid redirect port"),
network_conf: crate::data::network::NetworkConfigData::from_conf(oj_rc_core::ConfigProvider::<()>::network_config(conf)),
}
}
fn enter_match(&self, key: &QueueKey, players: &Vec<QueueUser>) {
use std::hash::Hasher;
let mut hasher = std::hash::DefaultHasher::new();
key.hash(&mut hasher);
let guid = oj_rc_core::persist::user::uuid_sanitize(hasher.finish() as i64);
let guid_str = oj_rc_core::persist::user::i64_as_uuid_str(guid);
let player_datas = players.iter().map(|x| x.player.clone()).collect();
let enter_battle_ev = crate::events::battle_enter::BattleEnter {
host: self.hostname.clone(),
port: self.hostport,
map: key.map.clone(),
mode: key.mode,
guid: guid_str,
is_ranked: false,
is_custom: false,
visibility: Some(key.visibility),
auto_heal: key.auto_heal,
player_datas,
network_config: self.network_conf.clone(),
};
let arc_event = std::sync::Arc::new(enter_battle_ev);
for player in players.iter() {
tokio::spawn(Self::send_events_to_player(arc_event.clone(), player.emitter.clone()));
}
}
async fn send_events_to_player(enter_event: std::sync::Arc<crate::events::battle_enter::BattleEnter>, sender: polariton_server::events::EventEmitter) {
const WAIT_BEFORE_ENTER: std::time::Duration = std::time::Duration::from_secs(2);
if sender.emit(crate::events::battle_found::BattleFound) {
tokio::time::sleep(WAIT_BEFORE_ENTER).await;
sender.emit(enter_event.as_ref());
}
}
pub async fn join_queue(&self, map: String, mode: oj_rc_core::data::game_mode::GameMode, visibility: oj_rc_core::data::game_mode::MapVisibility, auto_heal: bool, user: &(dyn oj_rc_core::persist::user::User<()> + Send + Sync), event_emitter: polariton_server::events::EventEmitter) {
if !self.is_enabled {
event_emitter.emit(crate::events::enqueue_error::QueueJoinError {
code: oj_rc_core::data::error_codes::LobbyReasonCode::NoSuitableLobbyFound as i16,
text: "Multiplayer is not enabled".to_owned(),
});
return;
}
let key = QueueKey {
map, mode, visibility, auto_heal,
};
match user.player_data().await {
Ok(player_data) => {
let new_player = QueueUser {
emitter: event_emitter,
player: player_data,
};
let mut lock = self.users_in_queue.lock().unwrap();
let players = if let Some(players) = lock.get_mut(&key) {
players.push(new_player);
players
} else {
lock.insert(key.clone(), vec![new_player]);
lock.get(&key).unwrap()
};
if players.len() >= self.users_per_game {
self.enter_match(&key, players);
lock.remove(&key);
}
},
Err(e) => {
event_emitter.emit(crate::events::enqueue_error::QueueJoinError {
code: e.error_code(),
text: e.error_msg().map(|x| x.to_owned()).unwrap_or_else(|| "Unknown queue join error".to_owned()),
});
}
}
}
}

View File

@@ -1,8 +1,11 @@
#![forbid(unsafe_code)]
mod cli;
mod lobby;
pub use lobby::QueueHandler;
mod data;
mod operations;
mod events;
use oj_polariton_auth::Handshake;
use tokio::net;
@@ -13,8 +16,8 @@ use polariton::operation::{OperationResponse, Typed};
pub struct InitConfig {
pub config: oj_rc_core::persist::config::ConfigImpl,
pub users: std::sync::Arc<oj_rc_core::persist::user::UserImpl>,
pub factory: std::sync::Arc<oj_rc_core::factory::Factory>,
pub parsers: oj_rc_core::cubes::CubeParsers,
pub queue: std::sync::Arc<QueueHandler>,
}
pub type UserTy = oj_rc_core::UserState<()>;
@@ -27,14 +30,14 @@ async fn main() -> std::io::Result<()> {
let config = oj_rc_core::persist::config::ConfigImpl::load(&args.assets).expect("Bad config data");
let users = std::sync::Arc::new(oj_rc_core::persist::user::UserImpl::load(&args.data, &config).await.expect("Bad user data"));
let factory = std::sync::Arc::new(<oj_rc_core::persist::config::ConfigImpl as oj_rc_core::ConfigProvider<()>>::factory::<'_, '_>(&config).await.expect("Bad vehicle factory (CRF) config"));
let queue = std::sync::Arc::new(QueueHandler::new(&config, &args.redirect));
let parsers = oj_rc_core::cubes::CubeParsers::new(&config);
let init_ctx = InitConfig {
config,
users,
factory,
parsers,
queue,
};
let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler(&init_ctx), polariton_server::events::EventsHandler::new()));

View File

@@ -13,14 +13,16 @@ const EVENT_TO_JOIN_PARAM_KEY: u8 = 41; // str; in
const ESTIMATED_QUEUE_TIME_PARAM_KEY: u8 = 13; // int (seconds); out
const PERSONAL_RANKING_PARAM_KEY: u8 = 17; // double; out
pub(super) struct QueueJoinProvider;
pub(super) struct QueueJoinProvider {
queue_handler: std::sync::Arc<crate::QueueHandler>,
}
#[async_trait::async_trait]
impl <C: Send + 'static> SimpleOperation<C> for QueueJoinProvider {
type User = crate::UserTy;
const CODE: u8 = CODE;
async fn handle(&self, params: ParameterTable<C>, _user: &Self::User) -> Result<ParameterTable<C>, SimpleOpError> {
async fn handle(&self, params: ParameterTable<C>, user: &Self::User) -> Result<ParameterTable<C>, SimpleOpError> {
let mut params = params.to_dict();
if let Some(Typed::Str(group_id)) = params.remove(&GROUP_ID_PARAM_KEY) {
if let Some(Typed::Int(slot_id)) = params.remove(&GARAGE_SLOT_PARAM_KEY) {
@@ -32,6 +34,16 @@ impl <C: Send + 'static> SimpleOperation<C> for QueueJoinProvider {
log::debug!("Got lobby join queue request of platoon {} ({} players, is_leader:{}) slot {} lobby {:?} event {}", group_id.string, group_size, is_leader, slot_id, lobby_ty, event_to_join.string);
params.insert(ESTIMATED_QUEUE_TIME_PARAM_KEY, Typed::Int(42));
params.insert(PERSONAL_RANKING_PARAM_KEY, Typed::Double(42.0));
let events = user.event_sender();
let user_info = user.user()?;
self.queue_handler.join_queue(
"FIXME_map".to_owned(),
oj_rc_core::data::game_mode::GameMode::BattleArena, // FIXME
oj_rc_core::data::game_mode::MapVisibility::Good, // FIXME
true, // FIXME
user_info.as_ref().as_ref(),
events.to_owned(),
).await;
}
}
}
@@ -42,6 +54,8 @@ impl <C: Send + 'static> SimpleOperation<C> for QueueJoinProvider {
}
}
pub(super) fn join_queue_provider<C: Send + 'static>() -> SimpleOpImpl<C, crate::UserTy, QueueJoinProvider> {
SimpleOpImpl::new(QueueJoinProvider)
pub(super) fn join_queue_provider<C: Send + 'static>(queue_handler: &std::sync::Arc<crate::QueueHandler>) -> SimpleOpImpl<C, crate::UserTy, QueueJoinProvider> {
SimpleOpImpl::new(QueueJoinProvider {
queue_handler: queue_handler.to_owned(),
})
}

View File

@@ -5,12 +5,12 @@ mod join_queue;
use polariton_server::operations::OperationsHandler;
pub fn handler(_init_ctx: &crate::InitConfig) -> OperationsHandler<crate::UserTy> {
pub fn handler(init_ctx: &crate::InitConfig) -> OperationsHandler<crate::UserTy> {
OperationsHandler::<crate::UserTy>::new()
.modify(oj_rc_core::polariton::RcOpModifier)
.add(more_auth::MoreLobbyAuth)
//.add(eac::EacChallengeIgnorer)
//.add(polariton_server::operations::Ack::<2, _>::default())
.add(no_quit::quit_blocker_provider())
.add(join_queue::join_queue_provider())
.add(join_queue::join_queue_provider(&init_ctx.queue))
}