~starkingdoms/starkingdoms

5eaa81cc1ccc43e7b1e086071a3e9b32c6dd8568 — c0repwn3r 2 years ago 6cb26db
recv position and planet data on the client
3 files changed, 61 insertions(+), 25 deletions(-)

M client/src/lib.rs
M protocol/src/lib.rs
M server/src/handler.rs
M client/src/lib.rs => client/src/lib.rs +24 -24
@@ 2,10 2,10 @@ use std::error::Error;

use futures::stream::{SplitSink, SplitStream};
use futures::StreamExt;
use log::{error, info, Level, trace, warn};
use log::{debug, error, info, Level, trace, warn};
use wasm_bindgen::prelude::*;
use ws_stream_wasm::{WsErr, WsMessage, WsMeta, WsStream};
use starkingdoms_protocol::State;
use starkingdoms_protocol::{Planet, State};
use starkingdoms_protocol::PROTOCOL_VERSION;
use starkingdoms_protocol::MessageS2C;
use starkingdoms_protocol::MessageC2S;


@@ 32,10 32,15 @@ extern {
    pub fn alert(s: &str);
}

#[derive(Debug)]
pub struct Client {
    pub client_data: Option<ClientData>
    pub client_data: Option<ClientData>,
    pub planets: Vec<Planet>,
    pub x: f64,
    pub y: f64
}

#[derive(Debug)]
pub struct ClientData {
    pub state: State,
    pub tx: SplitSink<WsStream, WsMessage>,


@@ 48,7 53,9 @@ pub const PONG_MAX_TIMEOUT: u64 = 5;
lazy_static! {
    pub static ref CLIENT: Arc<RwLock<Client>> = Arc::new(RwLock::new(Client {
        client_data: None,
        renderer: None
        planets: vec![],
        x: 0f64,
        y: 0f64
    }));
}



@@ 74,31 81,11 @@ pub async fn rust_init(gateway: &str, username: &str) -> Result<(), JsValue> {

    let mut client = CLIENT.write().unwrap();

    set_status("Initializing render subsystem...");
    info!("Starting renderer");

    let renderer = match WebRenderer::init().await {
        Ok(renderer) => renderer,
        Err(e) => {
            error!("Error initializing WebRenderer: {}", e);
            return Err(JsValue::from_str(&e.to_string()));
        }
    };

    client.renderer = Some(renderer);

    info!("StarKingdoms client set up successfully");

    Ok(())
}

fn draw(context: &WebGl2RenderingContext, vert_count: i32) {
    context.clear_color(0.0, 0.0, 0.0, 1.0);
    context.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);

    context.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, vert_count);
}

#[async_recursion(?Send)]
pub async fn main(gateway: &str, username: &str, backoff: i32) -> Result<(), Box<dyn Error>> {
    if backoff != 1 {


@@ 238,6 225,14 @@ pub async fn update_socket() -> Result<(), JsError> {
            MessageS2C::Pong {} => {
                client_data.pong_timeout = (js_sys::Date::now() as u64 / 1000) + PONG_MAX_TIMEOUT
            },
            MessageS2C::PlanetData { planets } => {
                debug!("updated planet information {:?}", planets);
                client.planets = planets;
            },
            MessageS2C::Position { x, y } => {
                client.x = x;
                client.y = y;
            }
            _ => {
                warn!("server sent unexpected packet {:?}, ignoring", msg);
            }


@@ 267,4 262,9 @@ pub fn sleep(ms: i32) -> js_sys::Promise {

pub async fn wait_for(promise: js_sys::Promise) -> JsFuture {
    wasm_bindgen_futures::JsFuture::from(promise)
}

#[wasm_bindgen]
pub fn version() -> u32 {
    PROTOCOL_VERSION
}
\ No newline at end of file

M protocol/src/lib.rs => protocol/src/lib.rs +17 -0
@@ 49,6 49,10 @@ pub enum MessageS2C {
    Position {
        x: f64,
        y: f64,
    },

    PlanetData {
        planets: Vec<Planet>
    }
}



@@ 62,6 66,19 @@ pub enum GoodbyeReason {
    Done,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Planet {
    pub planet_type: PlanetType,
    pub x: f64,
    pub y: f64,
    pub radius: f64
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum PlanetType {
    Earth
}

pub fn pc2s(pkt: &MessageC2S) -> Vec<u8> {
    rmp_serde::to_vec(pkt).unwrap()
}

M server/src/handler.rs => server/src/handler.rs +20 -1
@@ 8,7 8,7 @@ use log::{error, info, warn};
use tokio::sync::mpsc::Receiver;
use tokio_tungstenite::WebSocketStream;
use tungstenite::Message;
use starkingdoms_protocol::{GoodbyeReason, MessageC2S, MessageS2C, PROTOCOL_VERSION, State};
use starkingdoms_protocol::{GoodbyeReason, MessageC2S, MessageS2C, Planet, PlanetType, PROTOCOL_VERSION, State};
use starkingdoms_protocol::GoodbyeReason::PingPongTimeout;
use crate::manager::{ClientHandlerMessage, ClientManager};
use crate::{send, recv};


@@ 90,6 90,25 @@ pub async fn handle_client(mgr: ClientManager, remote_addr: SocketAddr, mut rx: 
                                }).await?;
                            state = next_state;
                            username = requested_username;

                            // TODO: Proper planet and position data
                            // TODO: This is only for testing of the planet rendering code
                            // TODO: !!!!!!!!!! REMOVE THIS WHEN PLANETS ACTUALLY EXIST !!!!!!!!!!
                            send!(client_tx, &MessageS2C::PlanetData {
                                planets: vec![
                                    Planet {
                                        planet_type: PlanetType::Earth,
                                        radius: 1f64,
                                        x: 0f64,
                                        y: 0f64
                                    }
                                ]
                            }).await?;
                            send!(client_tx, &MessageS2C::Position {
                                x: 1.5f64,
                                y: 1.5f64
                            }).await?;
                            // TODO: Remove above testing code when planets, yk, actually exist
                        },
                        MessageC2S::Goodbye { reason } => {
                            info!("client sent goodbye: {:?}", reason);