~starkingdoms/starkingdoms

ef79179a3db07911e0ef332d94334803aa7ec369 — core 2 years ago e3bbb13
formatting and join messages
3 files changed, 111 insertions(+), 59 deletions(-)

M server/src/macros.rs
M server/src/main.rs
M server/src/packet.rs
M server/src/macros.rs => server/src/macros.rs +2 -2
@@ 3,7 3,7 @@ macro_rules! err_or_cont {
    ($expr:expr) => {
        match $expr {
            Ok(n) => n,
            Err(_) => continue
            Err(_) => continue,
        }
    };
}


@@ 12,7 12,7 @@ macro_rules! some_or_cont {
    ($expr:expr) => {
        match $expr {
            Some(n) => n,
            None => continue
            None => continue,
        }
    };
}

M server/src/main.rs => server/src/main.rs +99 -47
@@ 2,15 2,15 @@ use std::net::Ipv4Addr;

use bevy::utils::tracing;
use bevy::{ecs::event::ManualEventReader, prelude::*};
use bevy_twite::{twite::frame::MessageType, ServerEvent, TwiteServerConfig, TwiteServerPlugin};
use bevy_rapier2d::prelude::*;
use bevy_twite::{twite::frame::MessageType, ServerEvent, TwiteServerConfig, TwiteServerPlugin};
use component::*;
use packet::*;
use rand::Rng;

pub mod component;
pub mod packet;
pub mod macros;
pub mod packet;

const SCALE: f32 = 10.0;
const EARTH_SIZE: f32 = 1000.0;


@@ 25,7 25,10 @@ fn main() {
    );

    App::new()
        .insert_resource(TwiteServerConfig { addr: Ipv4Addr::new(0, 0, 0, 0), port: 3000 })
        .insert_resource(TwiteServerConfig {
            addr: Ipv4Addr::new(0, 0, 0, 0),
            port: 3000,
        })
        .add_plugins(MinimalPlugins)
        .insert_resource(RapierConfiguration {
            gravity: Vect { x: 0., y: 0. },


@@ 77,7 80,11 @@ fn on_message(
                        let mut rng = rand::thread_rng();
                        rng.gen::<f32>() * std::f32::consts::PI * 2.
                    };
                    let mut transform = Transform::from_xyz(angle.cos() * 1100. / SCALE, angle.sin() * 1100. / SCALE, 0.0);
                    let mut transform = Transform::from_xyz(
                        angle.cos() * 1100. / SCALE,
                        angle.sin() * 1100. / SCALE,
                        0.0,
                    );
                    transform.rotate_z(angle);
                    let id = commands
                        .spawn(PlayerBundle {


@@ 85,26 92,38 @@ fn on_message(
                                part_type: PartType::Hearty,
                                transform: TransformBundle::from(transform),
                            },
                            player: Player { addr: *addr, username: username.to_string() },
                            player: Player {
                                addr: *addr,
                                username: username.to_string(),
                            },
                        })
                        .insert(Collider::cuboid(25.0 / SCALE, 25.0 / SCALE))
                        .insert(AdditionalMassProperties::Mass(10.0))
                        .insert(ExternalImpulse { impulse: Vec2::ZERO, torque_impulse: 0. })
                        .insert(ExternalImpulse {
                            impulse: Vec2::ZERO,
                            torque_impulse: 0.,
                        })
                        .insert(ReadMassProperties::default())
                        .insert(RigidBody::Dynamic)
                        .id().index();
                        .id()
                        .index();

                    // tell this player the planets
                    let mut planets = Vec::new();
                    for (entity, planet_type, transform) in planet_query.iter() {
                        let translation = transform.translation;
                        planets.push((entity.index(), Planet {
                            planet_type: *planet_type,
                            transform: proto_transform!(Transform::from_translation(translation * SCALE)),
                            radius: match *planet_type {
                                PlanetType::Earth => EARTH_SIZE
                            }
                        }));
                        planets.push((
                            entity.index(),
                            Planet {
                                planet_type: *planet_type,
                                transform: proto_transform!(Transform::from_translation(
                                    translation * SCALE
                                )),
                                radius: match *planet_type {
                                    PlanetType::Earth => EARTH_SIZE,
                                },
                            },
                        ));
                    }
                    let packet = Packet::PlanetPositions { planets };
                    let buf = serde_json::to_vec(&packet).unwrap();


@@ 115,9 134,7 @@ fn on_message(
                    for (entity, player) in &player_query {
                        players.push((entity.index(), player.username.clone()));
                    }
                    let packet = Packet::PlayerList {
                        players,
                    };
                    let packet = Packet::PlayerList { players };
                    let buf = serde_json::to_vec(&packet).unwrap();
                    event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));



@@ 128,25 145,41 @@ fn on_message(
                    };
                    let buf = serde_json::to_vec(&packet).unwrap();
                    event_queue.push(ServerEvent::Broadcast(MessageType::Text, buf));
                    let packet = Packet::Message {
                        message_type: packet::MessageType::Server,
                        actor: "SERVER".to_string(),
                        content: format!("{} has joined the server!", username),
                    };
                    let buf = serde_json::to_vec(&packet).unwrap();
                    event_queue.push(ServerEvent::Broadcast(MessageType::Text, buf));

                    // tell the player where parts are
                    let mut parts = Vec::new();
                    for (entity, part_type, transform) in &part_query {
                        parts.push((entity.index(), Part {
                            part_type: *part_type,
                            transform: proto_transform!(Transform::from_translation(transform.translation * SCALE)),
                        }));
                        parts.push((
                            entity.index(),
                            Part {
                                part_type: *part_type,
                                transform: proto_transform!(Transform::from_translation(
                                    transform.translation * SCALE
                                )),
                            },
                        ));
                    }
                    parts.push((id, Part {
                        part_type: PartType::Hearty,
                        transform: proto_transform!(Transform::from_translation(transform.translation * SCALE).with_rotation(transform.rotation)),
                    }));
                    let packet = Packet::PartPositions {
                        parts
                    };
                    parts.push((
                        id,
                        Part {
                            part_type: PartType::Hearty,
                            transform: proto_transform!(Transform::from_translation(
                                transform.translation * SCALE
                            )
                            .with_rotation(transform.rotation)),
                        },
                    ));
                    let packet = Packet::PartPositions { parts };
                    let buf = serde_json::to_vec(&packet).unwrap();
                    event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
                    

                    // and send the welcome message :)
                    let packet = Packet::Message {
                        message_type: packet::MessageType::Server,


@@ 179,7 212,11 @@ fn on_message(
                            content,
                        };
                        let buf = serde_json::to_vec(&packet).unwrap();
                        event_queue.push(ServerEvent::Send(target_player.addr, MessageType::Text, buf.clone()));
                        event_queue.push(ServerEvent::Send(
                            target_player.addr,
                            MessageType::Text,
                            buf.clone(),
                        ));
                        event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
                    } else {
                        // send to general chat


@@ 192,7 229,7 @@ fn on_message(
                        event_queue.push(ServerEvent::Broadcast(MessageType::Text, buf));
                    }
                }
                _ => continue
                _ => continue,
            }
        }
    }


@@ 214,13 251,15 @@ fn on_close(
                if player.addr == *addr {
                    commands.entity(entity).despawn();

                    let packet = Packet::PlayerLeave {
                        id: entity.index()
                    };
                    let packet = Packet::PlayerLeave { id: entity.index() };
                    let buf = serde_json::to_vec(&packet).unwrap();
                    for (in_entity, player) in &player_query {
                        if entity != in_entity {
                            packets.push(ServerEvent::Send(player.addr, MessageType::Text, buf.clone()));
                            packets.push(ServerEvent::Send(
                                player.addr,
                                MessageType::Text,
                                buf.clone(),
                            ));
                        }
                    }
                }


@@ 241,14 280,22 @@ fn on_position_change(
    let mut updated_parts = Vec::new();
    for (entity, part_type, transform) in part_query.iter() {
        let id = commands.entity(entity).id().index();
        updated_parts.push((id, Part {
            part_type: *part_type,
            transform: proto_transform!(Transform::from_translation(transform.translation * SCALE).with_rotation(transform.rotation)),
        }));
        updated_parts.push((
            id,
            Part {
                part_type: *part_type,
                transform: proto_transform!(Transform::from_translation(
                    transform.translation * SCALE
                )
                .with_rotation(transform.rotation)),
            },
        ));
    }

    if !updated_parts.is_empty() {
        let packet = Packet::PartPositions { parts: updated_parts };
        let packet = Packet::PartPositions {
            parts: updated_parts,
        };
        let buf = serde_json::to_vec(&packet).unwrap();

        packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));


@@ 257,13 304,18 @@ fn on_position_change(
    let mut planets = Vec::new();
    for (entity, planet_type, transform) in planet_query.iter() {
        let id = commands.entity(entity).id().index();
        planets.push((id, Planet {
            planet_type: *planet_type,
            transform: proto_transform!(Transform::from_translation(transform.translation * SCALE)),
            radius: match *planet_type {
                PlanetType::Earth => EARTH_SIZE,
            }
        }));
        planets.push((
            id,
            Planet {
                planet_type: *planet_type,
                transform: proto_transform!(Transform::from_translation(
                    transform.translation * SCALE
                )),
                radius: match *planet_type {
                    PlanetType::Earth => EARTH_SIZE,
                },
            },
        ));
    }

    if !planets.is_empty() {

M server/src/packet.rs => server/src/packet.rs +10 -10
@@ 1,11 1,11 @@
use serde::{Deserialize, Serialize};
use crate::component::{PartType, PlanetType};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct ProtoTransform {
    pub x: f32,
    pub y: f32,
    pub rot: f32
    pub rot: f32,
}
#[macro_export]
macro_rules! proto_transform {


@@ 13,7 13,7 @@ macro_rules! proto_transform {
        $crate::packet::ProtoTransform {
            x: $e.translation.x,
            y: $e.translation.y,
            rot: $e.rotation.to_euler(bevy::math::EulerRot::ZYX).0
            rot: $e.rotation.to_euler(bevy::math::EulerRot::ZYX).0,
        }
    };
}


@@ 27,7 27,7 @@ pub struct Planet {
#[derive(Debug, Serialize, Deserialize)]
pub struct Part {
    pub part_type: PartType,
    pub transform: ProtoTransform
    pub transform: ProtoTransform,
}

#[derive(Debug, Serialize, Deserialize)]


@@ 35,7 35,7 @@ pub enum MessageType {
    Server,
    Error,
    Chat,
    Direct
    Direct,
}

#[derive(Debug, Serialize, Deserialize)]


@@ 48,7 48,7 @@ pub enum Packet {
    },
    SendMessage {
        target: Option<String>,
        content: String
        content: String,
    },
    // clientbound
    SpawnPlayer {


@@ 59,10 59,10 @@ pub enum Packet {
        players: Vec<(u32, String)>,
    },
    PlanetPositions {
        planets: Vec<(u32, Planet)>
        planets: Vec<(u32, Planet)>,
    },
    PartPositions {
        parts: Vec<(u32, Part)>
        parts: Vec<(u32, Part)>,
    },
    PlayerLeave {
        id: u32,


@@ 70,6 70,6 @@ pub enum Packet {
    Message {
        message_type: MessageType,
        actor: String,
        content: String
    }
        content: String,
    },
}