~starkingdoms/starkingdoms

ref: 89c38c327e6eca6da0ab6d0d2b03d6af21b9f244 starkingdoms/crates/unified/src/server/mod.rs -rw-r--r-- 4.7 KiB
89c38c32ghostly_zsh fix: parts have initial velocity matching parent planet, and orbit indicator uses relative velocity 23 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
mod earth_parts;
mod gravity;
mod part;
mod heat;
mod drill;
mod craft;
mod damping;
pub mod planets;
pub mod player;
mod system_sets;
pub mod orbit;

use crate::server::craft::craft_plugin;
use crate::server::damping::damping_plugin;
use crate::server::drill::drill_plugin;
use crate::server::earth_parts::spawn_parts_plugin;
use crate::server::gravity::newtonian_gravity_plugin;
use crate::server::heat::conduction::heat_conduction_plugin;
use crate::server::heat::cooling::heat_cooling_plugin;
use crate::server::heat::radiation::heat_radiation_plugin;
use crate::server::part::part_management_plugin;
use crate::server::planets::planets_plugin;
use crate::server::player::player_management_plugin;
use crate::server::system_sets::{PlayerInputSet, WorldUpdateSet};
use aeronet::io::Session;
use aeronet::io::connection::{DisconnectReason, Disconnected, LocalAddr};
use aeronet::io::server::Server;
use aeronet_replicon::server::AeronetRepliconServer;
use aeronet_websocket::server::WebSocketServer;
use crate::prelude::*;
use bevy_replicon::prelude::Replicated;
use std::net::SocketAddr;
use crate::server::orbit::OrbitPlugin;
use crate::server::player::thrust::server_thrust_plugin;

pub struct ServerPlugin {
    pub bind: SocketAddr,
    pub max_clients: usize,
}
impl Plugin for ServerPlugin {
    fn build(&self, app: &mut App) {
        let config = self.websocket_config();

        app.add_systems(Startup, move |mut commands: Commands| {
            let server = commands
                .spawn(Name::new("ws-server-stk"))
                .insert(AeronetRepliconServer)
                .insert(Transform::from_xyz(0.0, 0.0, 0.0))
                .queue(WebSocketServer::open(config.clone()))
                .id();

            info!(entity_id=?server, "opening websocket server");
        })
        .add_observer(on_opened)
        .add_observer(on_connected)
        .add_observer(on_disconnected)
        .add_plugins(planets_plugin)
        .add_plugins(newtonian_gravity_plugin)
        .add_plugins(player_management_plugin)
        .add_plugins(spawn_parts_plugin)
        .add_plugins(part_management_plugin)
        .add_plugins(server_thrust_plugin)
        /*.add_plugins(heat_cooling_plugin)
        .add_plugins(heat_radiation_plugin)
        .add_plugins(heat_conduction_plugin)*/
        .add_plugins(drill_plugin)
        .add_plugins(craft_plugin)
        .add_plugins(OrbitPlugin)
        .add_plugins(damping_plugin)
        .configure_sets(Update, WorldUpdateSet.before(PlayerInputSet));
        //.configure_sets(Update, PlayerInputSet.before(PhysicsSet::SyncBackend));
    }
}
impl ServerPlugin {
    fn websocket_config(&self) -> aeronet_websocket::server::ServerConfig {
        aeronet_websocket::server::ServerConfig::builder()
            .with_bind_address(self.bind)
            .with_no_encryption()
    }
}

#[derive(Component, Debug)]
#[require(Replicated)]
pub struct ConnectedGameEntity {
    pub network_entity: Entity,
}
#[derive(Component)]
#[require(Replicated)]
pub struct ConnectedNetworkEntity {
    pub game_entity: Entity,
}

fn on_opened(trigger: On<Add, Server>, servers: Query<&LocalAddr>) {
    let server = trigger.event_target();
    let local_addr = servers.get(server).unwrap();
    info!(server_entity=?server, "websocket server opened on {:?}", *local_addr);
}
fn on_connected(
    trigger: On<Add, Session>,
    clients: Query<&ChildOf>,
    mut commands: Commands,
) {
    let client = trigger.event_target();
    let Ok(&ChildOf(server)) = clients.get(client) else {
        return;
    };
    info!(?client, ?server, "client connected");

    // spawn the player

    let player = commands
        .spawn(ConnectedGameEntity {
            network_entity: client,
        })
        .id();

    commands.entity(client).insert((
        Replicated,
        ConnectedNetworkEntity {
            game_entity: player,
        },
    ));
}
fn on_disconnected(
    trigger: On<Disconnected>,
    clients: Query<&ChildOf>,
    player_entity: Query<&ConnectedNetworkEntity>,
    mut commands: Commands,
) {
    let client = trigger.event_target();
    let Ok(&ChildOf(server)) = clients.get(client) else {
        return;
    };
    match &trigger.reason {
        DisconnectReason::ByUser(reason) => {
            info!(?client, ?server, ?reason, "client disconnected by user");
        }
        DisconnectReason::ByPeer(reason) => {
            info!(?client, ?server, ?reason, "client disconnected by peer");
        }
        DisconnectReason::ByError(err) => {
            warn!(?client, ?server, "client disconnected with error: {err:?}");
        }
    }
    let Ok(other_entity) = player_entity.get(client) else {
        return;
    };
    let Ok(mut commands) = commands.get_entity(other_entity.game_entity) else {
        return;
    };
    commands.despawn();
}