From 231a5ce21fcee9195fcc504ee672e4464d627c47 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Sun, 19 Oct 2025 20:21:27 +0200 Subject: Rename client-lib crate to game-core --- Cargo.lock | 36 ++-- Cargo.toml | 2 +- server/Cargo.toml | 2 +- server/bot/Cargo.toml | 2 +- server/bot/src/algos/customer.rs | 2 +- server/bot/src/algos/dishwasher.rs | 2 +- server/bot/src/algos/frank.rs | 2 +- server/bot/src/algos/simple.rs | 2 +- server/bot/src/algos/test.rs | 2 +- server/bot/src/algos/waiter.rs | 2 +- server/bot/src/lib.rs | 2 +- server/bot/src/main.rs | 2 +- server/client-lib/Cargo.toml | 23 --- server/client-lib/src/gamedata_index.rs | 45 ----- server/client-lib/src/lib.rs | 287 -------------------------------- server/client-lib/src/network/mod.rs | 21 --- server/client-lib/src/network/sync.rs | 148 ---------------- server/client-lib/src/network/tokio.rs | 147 ---------------- server/client-lib/src/spatial_index.rs | 72 -------- server/editor/Cargo.toml | 2 +- server/editor/src/main.rs | 2 +- server/game-core/Cargo.toml | 23 +++ server/game-core/src/gamedata_index.rs | 45 +++++ server/game-core/src/lib.rs | 286 +++++++++++++++++++++++++++++++ server/game-core/src/network/mod.rs | 21 +++ server/game-core/src/network/sync.rs | 148 ++++++++++++++++ server/game-core/src/network/tokio.rs | 147 ++++++++++++++++ server/game-core/src/spatial_index.rs | 72 ++++++++ server/registry/Cargo.toml | 2 +- server/registry/src/conn_test.rs | 2 +- server/src/entity/mod.rs | 2 +- server/src/entity/tag_minigame.rs | 2 +- server/src/interaction.rs | 2 +- server/src/server.rs | 2 +- 34 files changed, 779 insertions(+), 780 deletions(-) delete mode 100644 server/client-lib/Cargo.toml delete mode 100644 server/client-lib/src/gamedata_index.rs delete mode 100644 server/client-lib/src/lib.rs delete mode 100644 server/client-lib/src/network/mod.rs delete mode 100644 server/client-lib/src/network/sync.rs delete mode 100644 server/client-lib/src/network/tokio.rs delete mode 100644 server/client-lib/src/spatial_index.rs create mode 100644 server/game-core/Cargo.toml create mode 100644 server/game-core/src/gamedata_index.rs create mode 100644 server/game-core/src/lib.rs create mode 100644 server/game-core/src/network/mod.rs create mode 100644 server/game-core/src/network/sync.rs create mode 100644 server/game-core/src/network/tokio.rs create mode 100644 server/game-core/src/spatial_index.rs diff --git a/Cargo.lock b/Cargo.lock index c649f62d..3f61dacd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -990,26 +990,12 @@ dependencies = [ "anyhow", "clap", "env_logger", - "hurrycurry-client-lib", + "hurrycurry-game-core", "hurrycurry-protocol", "log", "rustls", ] -[[package]] -name = "hurrycurry-client-lib" -version = "3.0.0" -dependencies = [ - "anyhow", - "futures-util", - "hurrycurry-protocol", - "log", - "serde_json", - "tokio", - "tokio-tungstenite", - "tungstenite", -] - [[package]] name = "hurrycurry-data" version = "0.1.0" @@ -1050,7 +1036,7 @@ dependencies = [ "clap", "env_logger", "futures-util", - "hurrycurry-client-lib", + "hurrycurry-game-core", "hurrycurry-protocol", "log", "rustls", @@ -1062,6 +1048,20 @@ dependencies = [ "tokio-tungstenite", ] +[[package]] +name = "hurrycurry-game-core" +version = "3.0.0" +dependencies = [ + "anyhow", + "futures-util", + "hurrycurry-protocol", + "log", + "serde_json", + "tokio", + "tokio-tungstenite", + "tungstenite", +] + [[package]] name = "hurrycurry-locale" version = "0.1.0" @@ -1093,7 +1093,7 @@ version = "3.0.0" dependencies = [ "anyhow", "env_logger", - "hurrycurry-client-lib", + "hurrycurry-game-core", "hurrycurry-protocol", "log", "markup", @@ -1134,8 +1134,8 @@ dependencies = [ "futures-util", "get_if_addrs", "hurrycurry-bot", - "hurrycurry-client-lib", "hurrycurry-data", + "hurrycurry-game-core", "hurrycurry-locale", "hurrycurry-protocol", "igd", diff --git a/Cargo.toml b/Cargo.toml index 62bd0ef2..5ac28108 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = [ "server", "server/book-export", "server/bot", - "server/client-lib", + "server/game-core", "server/data", "server/discover", "server/editor", diff --git a/server/Cargo.toml b/server/Cargo.toml index add1329f..b6da3738 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -28,7 +28,7 @@ mdns-sd = { version = "0.15.1", optional = true } hurrycurry-locale = { path = "locale" } hurrycurry-protocol = { path = "protocol" } -hurrycurry-client-lib = { path = "client-lib" } +hurrycurry-game-core = { path = "game-core" } hurrycurry-bot = { path = "bot" } hurrycurry-data = { path = "data" } diff --git a/server/bot/Cargo.toml b/server/bot/Cargo.toml index c8717986..ad63f709 100644 --- a/server/bot/Cargo.toml +++ b/server/bot/Cargo.toml @@ -4,7 +4,7 @@ version = "3.0.0" edition = "2024" [dependencies] -hurrycurry-client-lib = { path = "../client-lib", features = ["tokio-network"] } +hurrycurry-game-core = { path = "../game-core", features = ["tokio-network"] } hurrycurry-protocol = { path = "../protocol" } log = "0.4.28" anyhow = "1.0.99" diff --git a/server/bot/src/algos/customer.rs b/server/bot/src/algos/customer.rs index bd757d9e..06dc373c 100644 --- a/server/bot/src/algos/customer.rs +++ b/server/bot/src/algos/customer.rs @@ -22,7 +22,7 @@ use crate::{ pathfinding::{Path, find_path}, random_float, }; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{ DemandIndex, Hand, ItemLocation, Message, PacketS, PlayerClass, PlayerID, Score, glam::{IVec2, Vec2}, diff --git a/server/bot/src/algos/dishwasher.rs b/server/bot/src/algos/dishwasher.rs index 94368558..5dbf954f 100644 --- a/server/bot/src/algos/dishwasher.rs +++ b/server/bot/src/algos/dishwasher.rs @@ -17,7 +17,7 @@ */ use super::simple::State; use crate::{BotAlgo, BotInput, algos::simple::Context, pathfinding::Path}; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{ItemIndex, PlayerID, glam::IVec2}; #[derive(Default)] diff --git a/server/bot/src/algos/frank.rs b/server/bot/src/algos/frank.rs index c815c75f..3515f96d 100644 --- a/server/bot/src/algos/frank.rs +++ b/server/bot/src/algos/frank.rs @@ -21,7 +21,7 @@ use crate::{ BotAlgo, BotInput, pathfinding::{Path, find_path_to_neighbour}, }; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{Message, PacketS, PlayerClass, PlayerID, glam::Vec2}; #[derive(Default)] diff --git a/server/bot/src/algos/simple.rs b/server/bot/src/algos/simple.rs index f8d01b3a..0145cfcb 100644 --- a/server/bot/src/algos/simple.rs +++ b/server/bot/src/algos/simple.rs @@ -19,7 +19,7 @@ use crate::{ BotAlgo, BotInput, pathfinding::{Path, find_path_to_neighbour}, }; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{ ItemIndex, Message, PlayerID, Recipe, RecipeIndex, TileIndex, glam::IVec2, }; diff --git a/server/bot/src/algos/test.rs b/server/bot/src/algos/test.rs index 361cf4ea..20abbabd 100644 --- a/server/bot/src/algos/test.rs +++ b/server/bot/src/algos/test.rs @@ -19,7 +19,7 @@ use crate::{ BotAlgo, BotInput, pathfinding::{Path, find_path_to_neighbour}, }; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{ItemIndex, Message, PlayerID, glam::IVec2}; use log::info; diff --git a/server/bot/src/algos/waiter.rs b/server/bot/src/algos/waiter.rs index 8fccd34a..9273eb42 100644 --- a/server/bot/src/algos/waiter.rs +++ b/server/bot/src/algos/waiter.rs @@ -17,7 +17,7 @@ */ use super::simple::State; use crate::{BotAlgo, BotInput, algos::simple::Context, pathfinding::Path}; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{ItemIndex, PlayerID, glam::IVec2}; use log::debug; diff --git a/server/bot/src/lib.rs b/server/bot/src/lib.rs index 927ac7b0..a3889021 100644 --- a/server/bot/src/lib.rs +++ b/server/bot/src/lib.rs @@ -19,7 +19,7 @@ pub mod algos; pub mod pathfinding; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_protocol::{ PacketS, PlayerID, glam::{IVec2, Vec2}, diff --git a/server/bot/src/main.rs b/server/bot/src/main.rs index 22dc2e3f..2fbf274f 100644 --- a/server/bot/src/main.rs +++ b/server/bot/src/main.rs @@ -18,7 +18,7 @@ use anyhow::Result; use clap::Parser; use hurrycurry_bot::{BotAlgo, BotInput, algos::ALGO_CONSTRUCTORS}; -use hurrycurry_client_lib::{Game, network::sync::Network}; +use hurrycurry_game_core::{Game, network::sync::Network}; use hurrycurry_protocol::{Character, Hand, ItemLocation, PacketC, PacketS, PlayerClass, PlayerID}; use log::warn; use std::{thread::sleep, time::Duration}; diff --git a/server/client-lib/Cargo.toml b/server/client-lib/Cargo.toml deleted file mode 100644 index 47a75e7e..00000000 --- a/server/client-lib/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "hurrycurry-client-lib" -version = "3.0.0" -edition = "2024" - -[dependencies] -hurrycurry-protocol = { path = "../protocol" } -tungstenite = { version = "0.27.0", optional = true, features = [ - "rustls-tls-native-roots", -] } -tokio-tungstenite = { version = "0.27.0", optional = true, features = [ - "rustls-tls-native-roots", -] } -tokio = { version = "1.47.1", features = ["net", "sync"], optional = true } -serde_json = "1.0.145" -log = "0.4.28" -anyhow = "1.0.99" -futures-util = { version = "0.3.31", optional = true } - -[features] -default = ["sync-network", "tokio-network"] -sync-network = ["dep:tungstenite"] -tokio-network = ["dep:tokio-tungstenite", "dep:tokio", "dep:futures-util"] diff --git a/server/client-lib/src/gamedata_index.rs b/server/client-lib/src/gamedata_index.rs deleted file mode 100644 index 8aa5e4af..00000000 --- a/server/client-lib/src/gamedata_index.rs +++ /dev/null @@ -1,45 +0,0 @@ -/* - Hurry Curry! - a game about cooking - Copyright (C) 2025 Hurry Curry! Contributors - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, version 3 of the License only. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -*/ -use hurrycurry_protocol::{Gamedata, ItemIndex, Recipe, RecipeIndex, TileIndex}; -use std::collections::HashMap; - -#[derive(Debug, Default)] -pub struct GamedataIndex { - pub tile_collide: Vec, - pub recipe_passive_by_input: HashMap>, -} - -impl GamedataIndex { - pub fn update(&mut self, data: &Gamedata) { - self.recipe_passive_by_input.clear(); - self.tile_collide.clear(); - - for tile in (0..data.tile_names.len()).map(TileIndex) { - self.tile_collide.push(!data.tile_walkable.contains(&tile)); - } - - for (ri, r) in data.recipes() { - if let Recipe::Passive { input, .. } = r { - self.recipe_passive_by_input - .entry(*input) - .or_default() - .push(ri); - } - } - } -} diff --git a/server/client-lib/src/lib.rs b/server/client-lib/src/lib.rs deleted file mode 100644 index 79c2ed01..00000000 --- a/server/client-lib/src/lib.rs +++ /dev/null @@ -1,287 +0,0 @@ -/* - Hurry Curry! - a game about cooking - Copyright (C) 2025 Hurry Curry! Contributors - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, version 3 of the License only. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -*/ -pub mod gamedata_index; -pub mod network; -pub mod spatial_index; - -use hurrycurry_protocol::{ - Character, Gamedata, Hand, ItemIndex, ItemLocation, Message, MessageTimeout, PacketC, - PlayerClass, PlayerID, RecipeIndex, Score, TileIndex, glam::IVec2, movement::MovementBase, -}; -use spatial_index::SpatialIndex; -use std::{ - collections::{BTreeSet, HashMap, HashSet, VecDeque}, - sync::Arc, - time::Instant, -}; - -use crate::gamedata_index::GamedataIndex; - -#[derive(Debug, Clone, PartialEq)] -pub struct Involvement { - pub position: f32, - pub speed: f32, - pub recipe: RecipeIndex, - pub players: BTreeSet, - pub warn: bool, -} - -#[derive(Debug, PartialEq)] -pub struct Item { - pub kind: ItemIndex, - pub active: Option, -} - -pub struct Tile { - pub kind: TileIndex, - pub item: Option, -} - -pub struct Player { - pub name: String, - pub class: PlayerClass, - pub character: Character, - pub interacting: Option<(ItemLocation, Hand)>, - pub items: Vec>, - pub communicate_persist: Option<(Message, MessageTimeout)>, - - pub movement: MovementBase, -} - -#[derive(Default)] -pub struct Game { - pub data: Arc, - pub data_index: GamedataIndex, - - pub tiles: HashMap, - pub players: HashMap, - pub end: Option, - pub lobby: bool, - pub environment_effects: HashSet, - pub score: Score, - pub player_id_counter: i64, - - pub players_spatial_index: SpatialIndex, - pub walkable: HashSet, - pub tile_index: HashMap>, - - pub events: VecDeque, -} - -impl Game { - pub fn apply_packet(&mut self, packet: PacketC) { - match packet { - PacketC::Data { data } => { - self.data = Arc::new(*data); - } - PacketC::AddPlayer { - id, - position, - character, - class, - name, - } => { - self.players.insert( - id, - Player { - name, - character, - class, - interacting: None, - items: (0..self.data.hand_count).map(|_| None).collect(), - communicate_persist: None, - movement: MovementBase::new(position), - }, - ); - } - PacketC::RemovePlayer { id } => { - self.players.remove(&id); - } - PacketC::Movement { - player, - pos, - rot, - boost, - dir, - } => { - if let Some(p) = self.players.get_mut(&player) { - p.movement.input(dir, boost); - p.movement.position = pos; - p.movement.rotation = rot; - } - } - PacketC::MoveItem { from, to } => { - if let Some(item) = self.get_item(to).map(|e| e.take()) { - if let Some(to) = self.get_item(from) { - *to = item; - } else { - // TODO perhaps restore to original position? - } - } - } - PacketC::SetItem { location, item } => { - let location = self.get_item(location); - if let Some(location) = location { - *location = item.map(|kind| Item { kind, active: None }); - } - } - PacketC::ClearProgress { item } => { - if let Some(Some(item)) = self.get_item(item) { - item.active = None; - } - } - PacketC::SetProgress { - item, - position, - players, - speed, - warn, - } => { - if let Some(Some(item)) = self.get_item(item) { - item.active = Some(Involvement { - players, - speed, - warn, - position, - recipe: RecipeIndex(0), - }); - } - } - PacketC::UpdateMap { - tile, - kind, - neighbors: _, - } => { - self.set_tile(tile, kind); - } - PacketC::Communicate { - player, - message, - timeout, - } => { - if let Some(timeout) = &timeout - && let Some(player) = self.players.get_mut(&player) - { - player.communicate_persist = message.to_owned().map(|m| (m, *timeout)); - } - } - PacketC::Score(score) => { - self.score = score; - } - PacketC::SetIngame { state: _, lobby } => { - self.lobby = lobby; - } - PacketC::Environment { effects } => { - self.environment_effects = effects; - } - _ => (), - } - } - - pub fn set_tile(&mut self, pos: IVec2, kind: Option) { - self.tiles.remove(&pos); - self.walkable.remove(&pos); - if let Some(prev) = self.tiles.get(&pos) { - if let Some(set) = self.tile_index.get_mut(&prev.kind) { - set.remove(&pos); - } - } - if let Some(kind) = kind { - self.tiles.insert(pos, Tile { kind, item: None }); - if self.data_index.tile_collide[kind.0] { - self.walkable.insert(pos); - } - self.tile_index.entry(kind).or_default().insert(pos); - } - self.events.push_back(PacketC::UpdateMap { - tile: pos, - kind, - neighbors: [ - self.tiles.get(&(pos + IVec2::NEG_Y)).map(|e| e.kind), - self.tiles.get(&(pos + IVec2::NEG_X)).map(|e| e.kind), - self.tiles.get(&(pos + IVec2::Y)).map(|e| e.kind), - self.tiles.get(&(pos + IVec2::X)).map(|e| e.kind), - ], - }); - } - - pub fn tick(&mut self, dt: f32) { - self.score.time_remaining -= dt as f64; - self.score.time_remaining -= self.score.time_remaining.max(0.); - - for (&pid, player) in &mut self.players { - player.movement.update(&self.walkable, dt); - if let Some((_, timeout)) = &mut player.communicate_persist { - timeout.remaining -= dt; - if timeout.remaining < 0. { - player.communicate_persist = None; - } - } - self.players_spatial_index - .update_entry(pid, player.movement.position); - } - - for player in self.players.values_mut() { - for item in player.items.iter_mut().flatten() { - if let Some(active) = &mut item.active { - active.position += active.speed; - } - } - } - for tile in self.tiles.values_mut() { - if let Some(item) = &mut tile.item - && let Some(active) = &mut item.active - { - active.position += active.speed; - } - } - - self.players_spatial_index.all(|p1, pos1| { - self.players_spatial_index.query(pos1, 2., |p2, _pos2| { - if let [Some(a), Some(b)] = self.players.get_disjoint_mut([&p1, &p2]) { - a.movement.collide(&mut b.movement, dt) - } - }) - }); - } - - pub fn get_item(&mut self, location: ItemLocation) -> Option<&mut Option> { - match location { - ItemLocation::Tile(pos) => Some(&mut self.tiles.get_mut(&pos)?.item), - ItemLocation::Player(pid, hand) => { - Some(self.players.get_mut(&pid)?.items.get_mut(hand.0)?) - } - } - } - pub fn get_unused_player_id(&mut self) -> PlayerID { - //! not possible because of join logic in server / multiple entities spawning bots - // let mut id = PlayerID(0); - // while self.players.contains_key(&id) { - // id.0 += 1; - // } - // id - self.player_id_counter += 1; - PlayerID(self.player_id_counter) - } -} - -impl From for Tile { - fn from(kind: TileIndex) -> Self { - Self { kind, item: None } - } -} diff --git a/server/client-lib/src/network/mod.rs b/server/client-lib/src/network/mod.rs deleted file mode 100644 index 45963567..00000000 --- a/server/client-lib/src/network/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - Hurry Curry! - a game about cooking - Copyright (C) 2025 Hurry Curry! Contributors - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, version 3 of the License only. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -*/ -#[cfg(feature = "sync-network")] -pub mod sync; -#[cfg(feature = "tokio-network")] -pub mod tokio; diff --git a/server/client-lib/src/network/sync.rs b/server/client-lib/src/network/sync.rs deleted file mode 100644 index 9854b58e..00000000 --- a/server/client-lib/src/network/sync.rs +++ /dev/null @@ -1,148 +0,0 @@ -/* - Hurry Curry! - a game about cooking - Copyright (C) 2025 Hurry Curry! Contributors - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, version 3 of the License only. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -*/ -use anyhow::Result; -use hurrycurry_protocol::{PacketC, PacketS, VERSION}; -use log::{debug, info, warn}; -use std::{collections::VecDeque, net::TcpStream}; -use tungstenite::{ - Message, WebSocket, - client::{IntoClientRequest, uri_mode}, - client_tls_with_config, - handshake::client::Request, - stream::{MaybeTlsStream, Mode}, - util::NonBlockingError, -}; - -pub struct Network { - sock: WebSocket>, - pub queue_in: VecDeque, - pub queue_out: VecDeque, - use_bincode: bool, -} - -impl Network { - pub fn connect(addr: &str) -> Result { - let (parts, _) = addr.into_client_request()?.into_parts(); - let mut builder = Request::builder() - .uri(parts.uri.clone().clone()) - .method(parts.method.clone()) - .version(parts.version); - *builder.headers_mut().unwrap() = parts.headers.clone(); - let request = builder.body(())?; - - let host = request.uri().host().unwrap_or("127.0.0.1"); - let host = if host.starts_with('[') { - &host[1..host.len() - 1] - } else { - host - }; - let port = request - .uri() - .port_u16() - .unwrap_or(match uri_mode(request.uri())? { - Mode::Plain => 27032, - Mode::Tls => 443, - }); - - info!("Connecting: host={host:?} port={port}"); - let stream = TcpStream::connect((host, port))?; - stream.set_nodelay(true)?; - - let (mut sock, _) = client_tls_with_config(request, stream, None, None)?; - - match sock.get_mut() { - MaybeTlsStream::Plain(s) => s.set_nonblocking(true)?, - MaybeTlsStream::Rustls(s) => s.sock.set_nonblocking(true)?, - _ => unreachable!(), - }; - - info!("Handshake complete."); - Ok(Self { - sock, - use_bincode: false, - queue_in: VecDeque::new(), - queue_out: VecDeque::new(), - }) - } - - pub fn poll(&mut self) -> anyhow::Result<()> { - loop { - self.queue_in.extend(match self.sock.read() { - Ok(Message::Text(packet)) => match serde_json::from_str(&packet) { - Ok(packet) => { - debug!("<- {packet:?}"); - if let PacketC::Version { - minor, - major, - supports_bincode, - } = &packet - && *minor == VERSION.0 - && *major == VERSION.1 - && *supports_bincode - { - info!("Binary protocol format enabled."); - self.use_bincode = true; - } - Some(packet) - } - Err(e) => { - warn!("invalid json packet: {e:?}"); - None - } - }, - Ok(Message::Binary(_packet)) => { - // match bincode::decode_from_slice(&packet, BINCODE_CONFIG) { - // Ok((packet, _)) => { - // debug!("<- {packet:?}"); - // Some(packet) - // } - // Err(e) => { - // warn!("invalid bincode packet: {e:?}"); - // None - // } - // } - None - } - Ok(_) => None, - Err(e) => { - if let Some(e) = e.into_non_blocking() { - warn!("{e:?}"); - None - } else { - break; - } - } - }); - } - - for packet in self.queue_out.drain(..) { - debug!("-> {packet:?}"); - // if self.use_bincode { - // self.sock.write(Message::Binary( - // bincode::encode_to_vec(&packet, BINCODE_CONFIG)?.into(), - // ))?; - // } else { - self.sock - .write(Message::Text(serde_json::to_string(&packet)?.into()))?; - // } - } - - self.sock.flush()?; - Ok(()) - } -} diff --git a/server/client-lib/src/network/tokio.rs b/server/client-lib/src/network/tokio.rs deleted file mode 100644 index 6e7f0902..00000000 --- a/server/client-lib/src/network/tokio.rs +++ /dev/null @@ -1,147 +0,0 @@ -/* - Hurry Curry! - a game about cooking - Copyright (C) 2025 Hurry Curry! Contributors - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, version 3 of the License only. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -*/ -use anyhow::{Result, anyhow}; -use futures_util::{ - SinkExt, TryStreamExt, - stream::{SplitSink, SplitStream, StreamExt}, -}; -use hurrycurry_protocol::{PacketC, PacketS, VERSION}; -use log::{debug, info, warn}; -use std::sync::atomic::{AtomicBool, Ordering}; -use tokio::{net::TcpStream, sync::RwLock}; -use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, client_async_tls_with_config}; -use tungstenite::{ - Message, - client::{IntoClientRequest, uri_mode}, - http::Request, - stream::Mode, -}; - -pub struct Network { - sock_recv: RwLock>>>, - sock_send: RwLock>, Message>>, - use_binary: AtomicBool, -} - -impl Network { - pub async fn connect(uri: &str) -> Result { - let (parts, _) = uri.into_client_request().unwrap().into_parts(); - let mut builder = Request::builder() - .uri(parts.uri.clone().clone()) - .method(parts.method.clone()) - .version(parts.version); - *builder.headers_mut().unwrap() = parts.headers.clone(); - let request = builder.body(()).unwrap(); - - let host = request.uri().host().unwrap(); - let host = if host.starts_with('[') { - &host[1..host.len() - 1] - } else { - host - }; - let port = request - .uri() - .port_u16() - .unwrap_or(match uri_mode(request.uri())? { - Mode::Plain => 27032, - Mode::Tls => 443, - }); - - info!("Connecting: host={host:?} port={port}"); - let stream = TcpStream::connect((host, port)).await?; - Self::connect_raw(stream, uri).await - } - pub async fn connect_raw(stream: TcpStream, uri: &str) -> Result { - let (parts, _) = uri.into_client_request()?.into_parts(); - let mut builder = Request::builder() - .uri(parts.uri.clone().clone()) - .method(parts.method.clone()) - .version(parts.version); - *builder.headers_mut().ok_or(anyhow!("???"))? = parts.headers.clone(); - let request = builder.body(())?; - - stream.set_nodelay(true)?; - let (sock, _) = client_async_tls_with_config(request, stream, None, None).await?; - info!("Handshake complete."); - let (sock_send, sock_recv) = sock.split(); - Ok(Self { - sock_recv: RwLock::new(sock_recv), - sock_send: RwLock::new(sock_send), - use_binary: false.into(), - }) - } - - pub async fn receive(&self) -> anyhow::Result> { - let mut g = self.sock_recv.write().await; - loop { - match g.try_next().await? { - Some(Message::Text(packet)) => match serde_json::from_str(&packet) { - Ok(packet) => { - debug!("<- {packet:?}"); - if let PacketC::Version { - minor, - major, - supports_bincode, - } = &packet - && *minor == VERSION.0 - && *major == VERSION.1 - && *supports_bincode - { - info!("Binary protocol format enabled."); - self.use_binary.store(true, Ordering::Relaxed); - } - return Ok(Some(packet)); - } - Err(e) => { - warn!("invalid json packet: {e:?}"); - } - }, - Some(Message::Binary(_packet)) => { - // match bincode::decode_from_slice(&packet, BINCODE_CONFIG) { - // Ok((packet, _)) => { - // debug!("<- {packet:?}"); - // return Ok(Some(packet)); - // } - // Err(e) => { - // warn!("invalid bincode packet: {e:?}"); - // } - // } - } - _ => (), - }; - } - } - pub async fn send(&self, packet: PacketS) -> anyhow::Result<()> { - debug!("-> {packet:?}"); - let mut g = self.sock_send.write().await; - // if self.use_binary.load(Ordering::Relaxed) { - // g.send(Message::Binary( - // bincode::encode_to_vec(&packet, BINCODE_CONFIG) - // .unwrap() - // .into(), - // )) - // .await?; - // } else { - g.send(Message::Text( - serde_json::to_string(&packet).unwrap().into(), - )) - .await?; - // } - Ok(()) - } -} diff --git a/server/client-lib/src/spatial_index.rs b/server/client-lib/src/spatial_index.rs deleted file mode 100644 index 8dd0cc22..00000000 --- a/server/client-lib/src/spatial_index.rs +++ /dev/null @@ -1,72 +0,0 @@ -/* - Hurry Curry! - a game about cooking - Copyright (C) 2025 Hurry Curry! Contributors - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, version 3 of the License only. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -*/ -use hurrycurry_protocol::glam::{IVec2, Vec2, ivec2}; -use std::{collections::HashMap, hash::Hash}; - -pub struct SpatialIndex { - entries: HashMap, - bins: HashMap>, -} - -impl SpatialIndex { - pub fn update_entry(&mut self, id: T, position: Vec2) { - self.remove_entry(id); - self.entries.insert(id, position); - let e = self.bins.entry(position.as_ivec2()).or_default(); - if !e.contains(&id) { - e.push(id); - } - } - pub fn remove_entry(&mut self, id: T) { - if let Some(pos) = self.entries.remove(&id) { - self.bins - .entry(pos.as_ivec2()) - .or_default() - .retain(|e| *e != id); - } - } - pub fn all(&self, mut cb: impl FnMut(T, Vec2)) { - for (&e, &pos) in &self.entries { - cb(e, pos) - } - } - pub fn query(&self, position: Vec2, radius: f32, mut cb: impl FnMut(T, Vec2)) { - let p = position.as_ivec2(); - let r = radius.ceil() as i32; - for xo in -r..=r { - for yo in -r..=r { - if let Some(bin) = self.bins.get(&(p + ivec2(xo, yo))) { - for &id in bin { - let p = *self.entries.get(&id).unwrap(); - if p.distance(position) < radius { - cb(id, p) - } - } - } - } - } - } -} -impl Default for SpatialIndex { - fn default() -> Self { - Self { - entries: Default::default(), - bins: Default::default(), - } - } -} diff --git a/server/editor/Cargo.toml b/server/editor/Cargo.toml index a4fb8bc2..80b939fe 100644 --- a/server/editor/Cargo.toml +++ b/server/editor/Cargo.toml @@ -20,4 +20,4 @@ shlex = "1.3.0" serde_yml = "0.0.12" hurrycurry-protocol = { path = "../protocol" } -hurrycurry-client-lib = { path = "../client-lib", features = ["sync-network"] } +hurrycurry-game-core = { path = "../game-core", features = ["sync-network"] } diff --git a/server/editor/src/main.rs b/server/editor/src/main.rs index be0fcbc5..86cb4b40 100644 --- a/server/editor/src/main.rs +++ b/server/editor/src/main.rs @@ -3,7 +3,7 @@ pub mod save; use anyhow::{Result, anyhow}; use clap::Parser; use futures_util::{SinkExt, StreamExt}; -use hurrycurry_client_lib::network::sync::Network; +use hurrycurry_game_core::network::sync::Network; use hurrycurry_protocol::{ Character, Gamedata, Hand, Message, PacketC, PacketS, PlayerClass, PlayerID, TileIndex, VERSION, diff --git a/server/game-core/Cargo.toml b/server/game-core/Cargo.toml new file mode 100644 index 00000000..8d764ab8 --- /dev/null +++ b/server/game-core/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "hurrycurry-game-core" +version = "3.0.0" +edition = "2024" + +[dependencies] +hurrycurry-protocol = { path = "../protocol" } +tungstenite = { version = "0.27.0", optional = true, features = [ + "rustls-tls-native-roots", +] } +tokio-tungstenite = { version = "0.27.0", optional = true, features = [ + "rustls-tls-native-roots", +] } +tokio = { version = "1.47.1", features = ["net", "sync"], optional = true } +serde_json = "1.0.145" +log = "0.4.28" +anyhow = "1.0.99" +futures-util = { version = "0.3.31", optional = true } + +[features] +default = ["sync-network", "tokio-network"] +sync-network = ["dep:tungstenite"] +tokio-network = ["dep:tokio-tungstenite", "dep:tokio", "dep:futures-util"] diff --git a/server/game-core/src/gamedata_index.rs b/server/game-core/src/gamedata_index.rs new file mode 100644 index 00000000..8aa5e4af --- /dev/null +++ b/server/game-core/src/gamedata_index.rs @@ -0,0 +1,45 @@ +/* + Hurry Curry! - a game about cooking + Copyright (C) 2025 Hurry Curry! Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +*/ +use hurrycurry_protocol::{Gamedata, ItemIndex, Recipe, RecipeIndex, TileIndex}; +use std::collections::HashMap; + +#[derive(Debug, Default)] +pub struct GamedataIndex { + pub tile_collide: Vec, + pub recipe_passive_by_input: HashMap>, +} + +impl GamedataIndex { + pub fn update(&mut self, data: &Gamedata) { + self.recipe_passive_by_input.clear(); + self.tile_collide.clear(); + + for tile in (0..data.tile_names.len()).map(TileIndex) { + self.tile_collide.push(!data.tile_walkable.contains(&tile)); + } + + for (ri, r) in data.recipes() { + if let Recipe::Passive { input, .. } = r { + self.recipe_passive_by_input + .entry(*input) + .or_default() + .push(ri); + } + } + } +} diff --git a/server/game-core/src/lib.rs b/server/game-core/src/lib.rs new file mode 100644 index 00000000..cc77e570 --- /dev/null +++ b/server/game-core/src/lib.rs @@ -0,0 +1,286 @@ +/* + Hurry Curry! - a game about cooking + Copyright (C) 2025 Hurry Curry! Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +*/ +pub mod gamedata_index; +pub mod network; +pub mod spatial_index; + +use hurrycurry_protocol::{ + Character, Gamedata, Hand, ItemIndex, ItemLocation, Message, MessageTimeout, PacketC, + PlayerClass, PlayerID, RecipeIndex, Score, TileIndex, glam::IVec2, movement::MovementBase, +}; +use spatial_index::SpatialIndex; +use std::{ + collections::{BTreeSet, HashMap, HashSet, VecDeque}, + sync::Arc, + time::Instant, +}; +use crate::gamedata_index::GamedataIndex; + +#[derive(Debug, Clone, PartialEq)] +pub struct Involvement { + pub position: f32, + pub speed: f32, + pub recipe: RecipeIndex, + pub players: BTreeSet, + pub warn: bool, +} + +#[derive(Debug, PartialEq)] +pub struct Item { + pub kind: ItemIndex, + pub active: Option, +} + +pub struct Tile { + pub kind: TileIndex, + pub item: Option, +} + +pub struct Player { + pub name: String, + pub class: PlayerClass, + pub character: Character, + pub interacting: Option<(ItemLocation, Hand)>, + pub items: Vec>, + pub communicate_persist: Option<(Message, MessageTimeout)>, + + pub movement: MovementBase, +} + +#[derive(Default)] +pub struct Game { + pub data: Arc, + pub data_index: GamedataIndex, + + pub tiles: HashMap, + pub players: HashMap, + pub end: Option, + pub lobby: bool, + pub environment_effects: HashSet, + pub score: Score, + pub player_id_counter: i64, + + pub players_spatial_index: SpatialIndex, + pub walkable: HashSet, + pub tile_index: HashMap>, + + pub events: VecDeque, +} + +impl Game { + pub fn apply_packet(&mut self, packet: PacketC) { + match packet { + PacketC::Data { data } => { + self.data = Arc::new(*data); + } + PacketC::AddPlayer { + id, + position, + character, + class, + name, + } => { + self.players.insert( + id, + Player { + name, + character, + class, + interacting: None, + items: (0..self.data.hand_count).map(|_| None).collect(), + communicate_persist: None, + movement: MovementBase::new(position), + }, + ); + } + PacketC::RemovePlayer { id } => { + self.players.remove(&id); + } + PacketC::Movement { + player, + pos, + rot, + boost, + dir, + } => { + if let Some(p) = self.players.get_mut(&player) { + p.movement.input(dir, boost); + p.movement.position = pos; + p.movement.rotation = rot; + } + } + PacketC::MoveItem { from, to } => { + if let Some(item) = self.get_item(to).map(|e| e.take()) { + if let Some(to) = self.get_item(from) { + *to = item; + } else { + // TODO perhaps restore to original position? + } + } + } + PacketC::SetItem { location, item } => { + let location = self.get_item(location); + if let Some(location) = location { + *location = item.map(|kind| Item { kind, active: None }); + } + } + PacketC::ClearProgress { item } => { + if let Some(Some(item)) = self.get_item(item) { + item.active = None; + } + } + PacketC::SetProgress { + item, + position, + players, + speed, + warn, + } => { + if let Some(Some(item)) = self.get_item(item) { + item.active = Some(Involvement { + players, + speed, + warn, + position, + recipe: RecipeIndex(0), + }); + } + } + PacketC::UpdateMap { + tile, + kind, + neighbors: _, + } => { + self.set_tile(tile, kind); + } + PacketC::Communicate { + player, + message, + timeout, + } => { + if let Some(timeout) = &timeout + && let Some(player) = self.players.get_mut(&player) + { + player.communicate_persist = message.to_owned().map(|m| (m, *timeout)); + } + } + PacketC::Score(score) => { + self.score = score; + } + PacketC::SetIngame { state: _, lobby } => { + self.lobby = lobby; + } + PacketC::Environment { effects } => { + self.environment_effects = effects; + } + _ => (), + } + } + + pub fn set_tile(&mut self, pos: IVec2, kind: Option) { + self.tiles.remove(&pos); + self.walkable.remove(&pos); + if let Some(prev) = self.tiles.get(&pos) { + if let Some(set) = self.tile_index.get_mut(&prev.kind) { + set.remove(&pos); + } + } + if let Some(kind) = kind { + self.tiles.insert(pos, Tile { kind, item: None }); + if self.data_index.tile_collide[kind.0] { + self.walkable.insert(pos); + } + self.tile_index.entry(kind).or_default().insert(pos); + } + self.events.push_back(PacketC::UpdateMap { + tile: pos, + kind, + neighbors: [ + self.tiles.get(&(pos + IVec2::NEG_Y)).map(|e| e.kind), + self.tiles.get(&(pos + IVec2::NEG_X)).map(|e| e.kind), + self.tiles.get(&(pos + IVec2::Y)).map(|e| e.kind), + self.tiles.get(&(pos + IVec2::X)).map(|e| e.kind), + ], + }); + } + + pub fn tick(&mut self, dt: f32) { + self.score.time_remaining -= dt as f64; + self.score.time_remaining -= self.score.time_remaining.max(0.); + + for (&pid, player) in &mut self.players { + player.movement.update(&self.walkable, dt); + if let Some((_, timeout)) = &mut player.communicate_persist { + timeout.remaining -= dt; + if timeout.remaining < 0. { + player.communicate_persist = None; + } + } + self.players_spatial_index + .update_entry(pid, player.movement.position); + } + + for player in self.players.values_mut() { + for item in player.items.iter_mut().flatten() { + if let Some(active) = &mut item.active { + active.position += active.speed; + } + } + } + for tile in self.tiles.values_mut() { + if let Some(item) = &mut tile.item + && let Some(active) = &mut item.active + { + active.position += active.speed; + } + } + + self.players_spatial_index.all(|p1, pos1| { + self.players_spatial_index.query(pos1, 2., |p2, _pos2| { + if let [Some(a), Some(b)] = self.players.get_disjoint_mut([&p1, &p2]) { + a.movement.collide(&mut b.movement, dt) + } + }) + }); + } + + pub fn get_item(&mut self, location: ItemLocation) -> Option<&mut Option> { + match location { + ItemLocation::Tile(pos) => Some(&mut self.tiles.get_mut(&pos)?.item), + ItemLocation::Player(pid, hand) => { + Some(self.players.get_mut(&pid)?.items.get_mut(hand.0)?) + } + } + } + pub fn get_unused_player_id(&mut self) -> PlayerID { + //! not possible because of join logic in server / multiple entities spawning bots + // let mut id = PlayerID(0); + // while self.players.contains_key(&id) { + // id.0 += 1; + // } + // id + self.player_id_counter += 1; + PlayerID(self.player_id_counter) + } +} + +impl From for Tile { + fn from(kind: TileIndex) -> Self { + Self { kind, item: None } + } +} diff --git a/server/game-core/src/network/mod.rs b/server/game-core/src/network/mod.rs new file mode 100644 index 00000000..45963567 --- /dev/null +++ b/server/game-core/src/network/mod.rs @@ -0,0 +1,21 @@ +/* + Hurry Curry! - a game about cooking + Copyright (C) 2025 Hurry Curry! Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +*/ +#[cfg(feature = "sync-network")] +pub mod sync; +#[cfg(feature = "tokio-network")] +pub mod tokio; diff --git a/server/game-core/src/network/sync.rs b/server/game-core/src/network/sync.rs new file mode 100644 index 00000000..9854b58e --- /dev/null +++ b/server/game-core/src/network/sync.rs @@ -0,0 +1,148 @@ +/* + Hurry Curry! - a game about cooking + Copyright (C) 2025 Hurry Curry! Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +*/ +use anyhow::Result; +use hurrycurry_protocol::{PacketC, PacketS, VERSION}; +use log::{debug, info, warn}; +use std::{collections::VecDeque, net::TcpStream}; +use tungstenite::{ + Message, WebSocket, + client::{IntoClientRequest, uri_mode}, + client_tls_with_config, + handshake::client::Request, + stream::{MaybeTlsStream, Mode}, + util::NonBlockingError, +}; + +pub struct Network { + sock: WebSocket>, + pub queue_in: VecDeque, + pub queue_out: VecDeque, + use_bincode: bool, +} + +impl Network { + pub fn connect(addr: &str) -> Result { + let (parts, _) = addr.into_client_request()?.into_parts(); + let mut builder = Request::builder() + .uri(parts.uri.clone().clone()) + .method(parts.method.clone()) + .version(parts.version); + *builder.headers_mut().unwrap() = parts.headers.clone(); + let request = builder.body(())?; + + let host = request.uri().host().unwrap_or("127.0.0.1"); + let host = if host.starts_with('[') { + &host[1..host.len() - 1] + } else { + host + }; + let port = request + .uri() + .port_u16() + .unwrap_or(match uri_mode(request.uri())? { + Mode::Plain => 27032, + Mode::Tls => 443, + }); + + info!("Connecting: host={host:?} port={port}"); + let stream = TcpStream::connect((host, port))?; + stream.set_nodelay(true)?; + + let (mut sock, _) = client_tls_with_config(request, stream, None, None)?; + + match sock.get_mut() { + MaybeTlsStream::Plain(s) => s.set_nonblocking(true)?, + MaybeTlsStream::Rustls(s) => s.sock.set_nonblocking(true)?, + _ => unreachable!(), + }; + + info!("Handshake complete."); + Ok(Self { + sock, + use_bincode: false, + queue_in: VecDeque::new(), + queue_out: VecDeque::new(), + }) + } + + pub fn poll(&mut self) -> anyhow::Result<()> { + loop { + self.queue_in.extend(match self.sock.read() { + Ok(Message::Text(packet)) => match serde_json::from_str(&packet) { + Ok(packet) => { + debug!("<- {packet:?}"); + if let PacketC::Version { + minor, + major, + supports_bincode, + } = &packet + && *minor == VERSION.0 + && *major == VERSION.1 + && *supports_bincode + { + info!("Binary protocol format enabled."); + self.use_bincode = true; + } + Some(packet) + } + Err(e) => { + warn!("invalid json packet: {e:?}"); + None + } + }, + Ok(Message::Binary(_packet)) => { + // match bincode::decode_from_slice(&packet, BINCODE_CONFIG) { + // Ok((packet, _)) => { + // debug!("<- {packet:?}"); + // Some(packet) + // } + // Err(e) => { + // warn!("invalid bincode packet: {e:?}"); + // None + // } + // } + None + } + Ok(_) => None, + Err(e) => { + if let Some(e) = e.into_non_blocking() { + warn!("{e:?}"); + None + } else { + break; + } + } + }); + } + + for packet in self.queue_out.drain(..) { + debug!("-> {packet:?}"); + // if self.use_bincode { + // self.sock.write(Message::Binary( + // bincode::encode_to_vec(&packet, BINCODE_CONFIG)?.into(), + // ))?; + // } else { + self.sock + .write(Message::Text(serde_json::to_string(&packet)?.into()))?; + // } + } + + self.sock.flush()?; + Ok(()) + } +} diff --git a/server/game-core/src/network/tokio.rs b/server/game-core/src/network/tokio.rs new file mode 100644 index 00000000..6e7f0902 --- /dev/null +++ b/server/game-core/src/network/tokio.rs @@ -0,0 +1,147 @@ +/* + Hurry Curry! - a game about cooking + Copyright (C) 2025 Hurry Curry! Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +*/ +use anyhow::{Result, anyhow}; +use futures_util::{ + SinkExt, TryStreamExt, + stream::{SplitSink, SplitStream, StreamExt}, +}; +use hurrycurry_protocol::{PacketC, PacketS, VERSION}; +use log::{debug, info, warn}; +use std::sync::atomic::{AtomicBool, Ordering}; +use tokio::{net::TcpStream, sync::RwLock}; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, client_async_tls_with_config}; +use tungstenite::{ + Message, + client::{IntoClientRequest, uri_mode}, + http::Request, + stream::Mode, +}; + +pub struct Network { + sock_recv: RwLock>>>, + sock_send: RwLock>, Message>>, + use_binary: AtomicBool, +} + +impl Network { + pub async fn connect(uri: &str) -> Result { + let (parts, _) = uri.into_client_request().unwrap().into_parts(); + let mut builder = Request::builder() + .uri(parts.uri.clone().clone()) + .method(parts.method.clone()) + .version(parts.version); + *builder.headers_mut().unwrap() = parts.headers.clone(); + let request = builder.body(()).unwrap(); + + let host = request.uri().host().unwrap(); + let host = if host.starts_with('[') { + &host[1..host.len() - 1] + } else { + host + }; + let port = request + .uri() + .port_u16() + .unwrap_or(match uri_mode(request.uri())? { + Mode::Plain => 27032, + Mode::Tls => 443, + }); + + info!("Connecting: host={host:?} port={port}"); + let stream = TcpStream::connect((host, port)).await?; + Self::connect_raw(stream, uri).await + } + pub async fn connect_raw(stream: TcpStream, uri: &str) -> Result { + let (parts, _) = uri.into_client_request()?.into_parts(); + let mut builder = Request::builder() + .uri(parts.uri.clone().clone()) + .method(parts.method.clone()) + .version(parts.version); + *builder.headers_mut().ok_or(anyhow!("???"))? = parts.headers.clone(); + let request = builder.body(())?; + + stream.set_nodelay(true)?; + let (sock, _) = client_async_tls_with_config(request, stream, None, None).await?; + info!("Handshake complete."); + let (sock_send, sock_recv) = sock.split(); + Ok(Self { + sock_recv: RwLock::new(sock_recv), + sock_send: RwLock::new(sock_send), + use_binary: false.into(), + }) + } + + pub async fn receive(&self) -> anyhow::Result> { + let mut g = self.sock_recv.write().await; + loop { + match g.try_next().await? { + Some(Message::Text(packet)) => match serde_json::from_str(&packet) { + Ok(packet) => { + debug!("<- {packet:?}"); + if let PacketC::Version { + minor, + major, + supports_bincode, + } = &packet + && *minor == VERSION.0 + && *major == VERSION.1 + && *supports_bincode + { + info!("Binary protocol format enabled."); + self.use_binary.store(true, Ordering::Relaxed); + } + return Ok(Some(packet)); + } + Err(e) => { + warn!("invalid json packet: {e:?}"); + } + }, + Some(Message::Binary(_packet)) => { + // match bincode::decode_from_slice(&packet, BINCODE_CONFIG) { + // Ok((packet, _)) => { + // debug!("<- {packet:?}"); + // return Ok(Some(packet)); + // } + // Err(e) => { + // warn!("invalid bincode packet: {e:?}"); + // } + // } + } + _ => (), + }; + } + } + pub async fn send(&self, packet: PacketS) -> anyhow::Result<()> { + debug!("-> {packet:?}"); + let mut g = self.sock_send.write().await; + // if self.use_binary.load(Ordering::Relaxed) { + // g.send(Message::Binary( + // bincode::encode_to_vec(&packet, BINCODE_CONFIG) + // .unwrap() + // .into(), + // )) + // .await?; + // } else { + g.send(Message::Text( + serde_json::to_string(&packet).unwrap().into(), + )) + .await?; + // } + Ok(()) + } +} diff --git a/server/game-core/src/spatial_index.rs b/server/game-core/src/spatial_index.rs new file mode 100644 index 00000000..8dd0cc22 --- /dev/null +++ b/server/game-core/src/spatial_index.rs @@ -0,0 +1,72 @@ +/* + Hurry Curry! - a game about cooking + Copyright (C) 2025 Hurry Curry! Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, version 3 of the License only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +*/ +use hurrycurry_protocol::glam::{IVec2, Vec2, ivec2}; +use std::{collections::HashMap, hash::Hash}; + +pub struct SpatialIndex { + entries: HashMap, + bins: HashMap>, +} + +impl SpatialIndex { + pub fn update_entry(&mut self, id: T, position: Vec2) { + self.remove_entry(id); + self.entries.insert(id, position); + let e = self.bins.entry(position.as_ivec2()).or_default(); + if !e.contains(&id) { + e.push(id); + } + } + pub fn remove_entry(&mut self, id: T) { + if let Some(pos) = self.entries.remove(&id) { + self.bins + .entry(pos.as_ivec2()) + .or_default() + .retain(|e| *e != id); + } + } + pub fn all(&self, mut cb: impl FnMut(T, Vec2)) { + for (&e, &pos) in &self.entries { + cb(e, pos) + } + } + pub fn query(&self, position: Vec2, radius: f32, mut cb: impl FnMut(T, Vec2)) { + let p = position.as_ivec2(); + let r = radius.ceil() as i32; + for xo in -r..=r { + for yo in -r..=r { + if let Some(bin) = self.bins.get(&(p + ivec2(xo, yo))) { + for &id in bin { + let p = *self.entries.get(&id).unwrap(); + if p.distance(position) < radius { + cb(id, p) + } + } + } + } + } + } +} +impl Default for SpatialIndex { + fn default() -> Self { + Self { + entries: Default::default(), + bins: Default::default(), + } + } +} diff --git a/server/registry/Cargo.toml b/server/registry/Cargo.toml index 8c5ad971..77ab7476 100644 --- a/server/registry/Cargo.toml +++ b/server/registry/Cargo.toml @@ -18,4 +18,4 @@ tokio-tungstenite = { version = "0.27.0", features = [ rustls = { version = "0.23.31", features = ["ring"] } hurrycurry-protocol = { path = "../protocol" } -hurrycurry-client-lib = { path = "../client-lib" } +hurrycurry-game-core = { path = "../game-core" } diff --git a/server/registry/src/conn_test.rs b/server/registry/src/conn_test.rs index e4f4fa63..bc371a10 100644 --- a/server/registry/src/conn_test.rs +++ b/server/registry/src/conn_test.rs @@ -16,7 +16,7 @@ */ use anyhow::{Context, Result, bail}; -use hurrycurry_client_lib::network::tokio::Network; +use hurrycurry_game_core::network::tokio::Network; use hurrycurry_protocol::PacketC; use log::info; use std::{ diff --git a/server/src/entity/mod.rs b/server/src/entity/mod.rs index 4bca9dc8..34815d0d 100644 --- a/server/src/entity/mod.rs +++ b/server/src/entity/mod.rs @@ -38,7 +38,7 @@ use campaign::{Gate, Map}; use conveyor::Conveyor; use customers::Customers; use environment_effect::{EnvironmentController, EnvironmentEffectController}; -use hurrycurry_client_lib::Game; +use hurrycurry_game_core::Game; use hurrycurry_data::{Serverdata, entities::EntityDecl}; use hurrycurry_locale::TrError; use hurrycurry_protocol::{Character, ItemLocation, PacketC, PacketS, PlayerID}; diff --git a/server/src/entity/tag_minigame.rs b/server/src/entity/tag_minigame.rs index 7c6c721f..a76b0511 100644 --- a/server/src/entity/tag_minigame.rs +++ b/server/src/entity/tag_minigame.rs @@ -17,7 +17,7 @@ */ use super::{Entity, EntityContext}; use anyhow::Result; -use hurrycurry_client_lib::{Item, Tile}; +use hurrycurry_game_core::{Item, Tile}; use hurrycurry_protocol::{ Hand, ItemIndex, ItemLocation, Message, PacketC, PlayerID, TileIndex, glam::IVec2, }; diff --git a/server/src/interaction.rs b/server/src/interaction.rs index dfe62121..a2e8643a 100644 --- a/server/src/interaction.rs +++ b/server/src/interaction.rs @@ -15,7 +15,7 @@ along with this program. If not, see . */ -use hurrycurry_client_lib::{Involvement, Item, gamedata_index::GamedataIndex}; +use hurrycurry_game_core::{Involvement, Item, gamedata_index::GamedataIndex}; use hurrycurry_protocol::{Gamedata, ItemLocation, PacketC, PlayerID, Recipe, Score, TileIndex}; use log::info; use std::collections::{BTreeSet, VecDeque}; diff --git a/server/src/server.rs b/server/src/server.rs index 1886715d..7ded8eb7 100644 --- a/server/src/server.rs +++ b/server/src/server.rs @@ -23,7 +23,7 @@ use crate::{ scoreboard::ScoreboardStore, }; use anyhow::{Context, Result}; -use hurrycurry_client_lib::{Game, Involvement, Item, Player, Tile}; +use hurrycurry_game_core::{Game, Involvement, Item, Player, Tile}; use hurrycurry_data::{Serverdata, index::DataIndex}; use hurrycurry_locale::{ FALLBACK_LOCALE, TrError, -- cgit v1.3