~starkingdoms/starkingdoms

ref: a032d20ee4fdccaa715bbde2cb73b318222ad6e1 starkingdoms/server/src/handler.rs -rw-r--r-- 32.2 KiB
a032d20e — c0repwn3r metrics 2 years 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
use crate::api::{load_player_data_from_api, save_player_data_to_api};
use crate::entity::{get_entity_id, Entity, EntityHandler};
use crate::manager::{ClientHandlerMessage, ClientManager, PhysicsData, Player, PlayerInput};
use crate::module::{AttachedModule, Module};
use crate::{recv, send, SCALE};
use async_std::net::TcpStream;
use async_std::{channel::Receiver, sync::RwLock};
use async_tungstenite::WebSocketStream;
use futures::stream::{SplitSink, SplitStream};
use futures::{FutureExt, SinkExt, StreamExt};
use log::{error, info, warn};
use nalgebra::{point, vector, Vector2};
use rand::Rng;
use rapier2d_f64::prelude::{
    Collider, ColliderBuilder, Isometry, MassProperties, RigidBodyBuilder, RigidBodyType,
};
use starkingdoms_protocol::goodbye_reason::GoodbyeReason;
use starkingdoms_protocol::message_s2c::{
    MessageS2CChat, MessageS2CGoodbye, MessageS2CHello, MessageS2CModuleAdd,
    MessageS2CModuleRemove, MessageS2CModuleTreeUpdate, MessageS2CModulesUpdate,
    MessageS2CPlanetData, MessageS2CPlayersUpdate, MessageS2CPong,
};

use protobuf::SpecialFields;
use starkingdoms_protocol::module::ModuleType;
use starkingdoms_protocol::state::State;
use starkingdoms_protocol::{MessageC2S, MessageS2C, PROTOCOL_VERSION};
use std::error::Error;
use std::f64::consts::PI;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tungstenite::Message;

pub async fn handle_client(
    mgr: ClientManager,
    entities: Arc<RwLock<EntityHandler>>,
    data: Arc<RwLock<PhysicsData>>,
    remote_addr: SocketAddr,
    rx: Receiver<ClientHandlerMessage>,
    mut client_tx: SplitSink<WebSocketStream<TcpStream>, Message>,
    mut client_rx: SplitStream<WebSocketStream<TcpStream>>,
) -> Result<(), Box<dyn Error>> {
    let mut state = State::Handshake;
    let mut username = String::new();
    let mut ping_timeout = SystemTime::now() + Duration::from_secs(10);

    loop {
        if let Ok(msg) = rx.recv().await {
            match msg {
                ClientHandlerMessage::Tick => {} // this intentionally does nothing,
                ClientHandlerMessage::ChatMessage { from, message } => {
                    if matches!(state, State::Play) {
                        let msg = MessageS2C::Chat(MessageS2CChat {
                            from,
                            message,
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                    }
                }
                ClientHandlerMessage::PlayersUpdate { players } => {
                    if matches!(state, State::Play) {
                        let msg = MessageS2C::PlayersUpdate(MessageS2CPlayersUpdate {
                            players,
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                    }
                }
                ClientHandlerMessage::PlanetData { planets } => {
                    if matches!(state, State::Play) {
                        let msg = MessageS2C::PlanetData(MessageS2CPlanetData {
                            planets,
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                    }
                }
                ClientHandlerMessage::ModulesUpdate { modules } => {
                    if matches!(state, State::Play) {
                        let msg = MessageS2C::ModulesUpdate(MessageS2CModulesUpdate {
                            modules,
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                    }
                }
                ClientHandlerMessage::ModuleTreeUpdate { modules } => {
                    if matches!(state, State::Play) {
                        let msg = MessageS2C::ModuleTreeUpdate(MessageS2CModuleTreeUpdate {
                            tree: modules,
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                    }
                }
            }
        } else {
            info!("channel closed, shutting down");
            break;
        }

        if ping_timeout < SystemTime::now() {
            error!("[{}] ping timeout", remote_addr);
            let msg = MessageS2C::Goodbye(MessageS2CGoodbye {
                reason: GoodbyeReason::PingPongTimeout.into(),
                special_fields: SpecialFields::default(),
            })
            .try_into()?;
            send!(client_tx, msg).await?;
            break;
        }

        if let Some(pkt) = recv!(client_rx)? {
            match state {
                State::UNKNOWN => unreachable!(),
                State::Handshake => {
                    match pkt {
                        MessageC2S::Hello(pkt) => {
                            info!("client sent hello");
                            // there is no way to not use unwrap here :/
                            #[allow(clippy::unwrap_used)]
                            if !matches!(pkt.next_state.unwrap(), State::Play) {
                                error!(
                                    "client sent unexpected state {:?} (expected: Play)",
                                    pkt.next_state
                                );
                                let msg = MessageS2C::Goodbye(MessageS2CGoodbye {
                                    reason: GoodbyeReason::UnexpectedNextState.into(),
                                    special_fields: SpecialFields::default(),
                                })
                                .try_into()?;
                                send!(client_tx, msg).await?;
                                break;
                            }

                            // check version
                            if pkt.version != PROTOCOL_VERSION {
                                error!(
                                    "client sent incompatible version {} (expected: {})",
                                    pkt.version, PROTOCOL_VERSION
                                );
                                let msg = MessageS2C::Goodbye(MessageS2CGoodbye {
                                    reason: GoodbyeReason::UnsupportedProtocol.into(),
                                    special_fields: SpecialFields::default(),
                                })
                                .try_into()?;
                                send!(client_tx, msg).await?;
                                break;
                            }

                            // determine if we can give them that username
                            {
                                if mgr
                                    .usernames
                                    .read()
                                    .await
                                    .values()
                                    .any(|u| *u == pkt.requested_username)
                                {
                                    error!(
                                        "client requested username {} but it is in use",
                                        pkt.requested_username
                                    );
                                    let msg: Vec<u8> = MessageS2C::Goodbye(MessageS2CGoodbye {
                                        reason: GoodbyeReason::UsernameTaken.into(),
                                        special_fields: SpecialFields::default(),
                                    })
                                    .try_into()?;
                                    send!(client_tx, msg).await?;
                                    break;
                                }
                            }

                            // username is fine
                            {
                                mgr.usernames
                                    .write()
                                    .await
                                    .insert(remote_addr, pkt.requested_username.clone());
                            }

                            let msg = MessageS2C::Hello(MessageS2CHello {
                                version: pkt.version,
                                given_username: pkt.requested_username.clone(),
                                special_fields: SpecialFields::default(),
                                next_state: pkt.next_state,
                            })
                            .try_into()?;

                            send!(client_tx, msg).await?;

                            state = pkt.next_state.unwrap();
                            username = pkt.requested_username;

                            // make player rigidbody
                            {
                                let mut data_handle = data.write().await;

                                let mut rigid_body_set = data_handle.rigid_body_set.clone();
                                let mut collider_set = data_handle.collider_set.clone();

                                let angle: f64 = {
                                    let mut rng = rand::thread_rng();
                                    rng.gen::<f64>() * PI * 2.
                                };
                                let player_body = RigidBodyBuilder::new(RigidBodyType::Dynamic)
                                    .translation(vector![
                                        angle.cos() * 2050. / SCALE,
                                        angle.sin() * 2050.0 / SCALE
                                    ])
                                    .rotation(angle + PI / 2.)
                                    .build();
                                let player_collider: Collider =
                                    ColliderBuilder::cuboid(25.0 / SCALE, 25.0 / SCALE)
                                        .mass_properties(MassProperties::new(
                                            point![0.0, 0.0],
                                            0.0001,
                                            0.005,
                                        ))
                                        .build();
                                let player_handle = rigid_body_set.insert(player_body);

                                collider_set.insert_with_parent(
                                    player_collider,
                                    player_handle,
                                    &mut rigid_body_set,
                                );

                                let mut player = Player {
                                    handle: player_handle,
                                    input: PlayerInput::default(),
                                    addr: remote_addr,
                                    auth_token: None,
                                    auth_user: None,
                                    children: [None, None, None, None],
                                };

                                let mut e_write_handle = entities.write().await;

                                if !pkt.user.is_empty() && !pkt.token.is_empty() {
                                    player.auth_token = Some(pkt.token.clone());
                                    player.auth_user = Some(pkt.user.clone());
                                    info!(
                                        "[{}] * Beamin: beaming in {} as {} with token {}",
                                        remote_addr, username, pkt.user, pkt.token
                                    );

                                    let player_data = match load_player_data_from_api(
                                        &pkt.token,
                                        &pkt.user,
                                        &std::env::var("STK_API_KEY")?,
                                    )
                                    .await
                                    {
                                        Ok(d) => d,
                                        Err(e) => {
                                            warn!(
                                                "[{}] * Beamin: ABORTED. API returned error: {}",
                                                remote_addr, e
                                            );
                                            e_write_handle
                                                .entities
                                                .insert(get_entity_id(), Entity::Player(player));
                                            continue;
                                        }
                                    };

                                    info!(
                                        "[{}] Beamin: loaded player data! {:?}",
                                        remote_addr, player_data
                                    );

                                    player.load_api_data(&player_data);
                                }

                                let player_id = get_entity_id();
                                e_write_handle
                                    .entities
                                    .insert(player_id, Entity::Player(player));

                                data_handle.rigid_body_set = rigid_body_set;
                                data_handle.collider_set = collider_set;
                            }
                        }
                        MessageC2S::Goodbye(pkt) => {
                            info!("client sent goodbye: {:?}", pkt.reason);
                            break;
                        }
                        _ => {
                            error!(
                                "client sent unexpected packet {:?} for state {:?}",
                                pkt, state
                            );
                            let msg = MessageS2C::Goodbye(MessageS2CGoodbye {
                                reason: GoodbyeReason::UnexpectedPacket.into(),
                                special_fields: SpecialFields::default(),
                            })
                            .try_into()?;
                            send!(client_tx, msg).await?;
                            break;
                        }
                    }
                }
                State::Play => match pkt {
                    MessageC2S::Hello { .. } => {
                        error!(
                            "client sent unexpected packet {:?} for state {:?}",
                            pkt, state
                        );
                        let msg = MessageS2C::Goodbye(MessageS2CGoodbye {
                            reason: GoodbyeReason::UnexpectedPacket.into(),
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                        break;
                    }
                    MessageC2S::Goodbye(pkt) => {
                        info!("client sent goodbye: {:?}", pkt.reason);
                        break;
                    }
                    MessageC2S::Chat(pkt) => {
                        info!("[{}] CHAT: [{}] {}", remote_addr, username, pkt.message);

                        let read_handle = mgr.handlers.read().await;

                        #[allow(clippy::significant_drop_in_scrutinee)] // i know
                        for (_addr, client_thread) in read_handle.iter() {
                            match client_thread
                                .tx
                                .send(ClientHandlerMessage::ChatMessage {
                                    from: username.clone(),
                                    message: pkt.message.clone(),
                                })
                                .await
                            {
                                Ok(_) => (),
                                Err(e) => {
                                    error!("unable to update a client thread: {}", e);
                                }
                            }
                        }
                    }
                    MessageC2S::Ping(_) => {
                        let msg = MessageS2C::Pong(MessageS2CPong {
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                        ping_timeout = SystemTime::now() + Duration::from_secs(10);
                    }
                    #[allow(clippy::significant_drop_tightening)]
                    // TODO: Remove when this lint is developed more
                    MessageC2S::Input(p) => {
                        let mut handle = entities.write().await;
                        let id = handle
                            .get_player_id(remote_addr)
                            .ok_or("could not get player id")?;

                        if let Entity::Player(ref mut me) = handle
                            .entities
                            .get_mut(&id)
                            .ok_or("player disconnected but continued to send packets")?
                        {
                            me.input.up = p.up_pressed;
                            me.input.down = p.down_pressed;
                            me.input.left = p.left_pressed;
                            me.input.right = p.right_pressed;
                        }
                    }
                    MessageC2S::AuthenticateAndBeamOut(p) => {
                        info!(
                            "[{}] * Beaming out {} as {} with realm token {}",
                            remote_addr, username, p.user_id, p.token
                        );

                        let player = entities
                            .read()
                            .await
                            .get_player(remote_addr)
                            .ok_or("Player sending messages after disconnect")?;

                        if Some(p.token) != player.auth_token || Some(p.user_id) != player.auth_user
                        {
                            warn!("[{}] invalid beamout packet, ignoring", remote_addr);
                            continue;
                        }

                        match save_player_data_to_api(
                            &player.as_api_data(),
                            &player
                                .auth_token
                                .ok_or("Tried to beamout without an auth token")?,
                            &player
                                .auth_user
                                .ok_or("Tried to beamout without setting a user")?,
                            &std::env::var("STK_API_KEY")?,
                        )
                        .await
                        {
                            Ok(_) => {
                                info!("[{}] * Beamed out successfully", remote_addr);
                                let msg = MessageS2C::Goodbye(MessageS2CGoodbye {
                                    reason: GoodbyeReason::Done.into(),
                                    special_fields: SpecialFields::default(),
                                })
                                .try_into()?;
                                send!(client_tx, msg).await?;
                                break;
                            }
                            Err(e) => {
                                error!("[{}] error beaming out: {}", remote_addr, e);
                            }
                        }
                    }
                    MessageC2S::MouseInput(_p) => {
                        //debug!("[{}] player input: {:?}", remote_addr, p);
                    }
                    #[allow(clippy::significant_drop_tightening)]
                    // TODO: Remove when this lint is developed more
                    MessageC2S::ModuleDetach(p) => {
                        let mut entities = entities.write().await;
                        let mut data_handle = data.write().await;
                        let module: Option<AttachedModule>;
                        //debug!("[{}] detach: {:?}", remote_addr, p);
                        //debug!("[{}] {:?}", remote_addr, entities.entities);

                        if let Some(Entity::AttachedModule(p_module)) =
                            entities.entities.get_mut(&p.module_id)
                        {
                            module = Some(p_module.clone());
                        } else {
                            warn!("[{}] attempted to detach nonexistent module", remote_addr);
                            continue;
                        }

                        let player_id = entities
                            .get_player_id(remote_addr)
                            .ok_or("player does not exist")?;
                        let module_id = AttachedModule::detach(
                            &mut data_handle,
                            &mut entities,
                            player_id,
                            &module.ok_or("cannot detach module that doesn't exist")?,
                        )
                        .ok_or("detach failed")?;
                        let module = entities
                            .get_module_from_id(module_id)
                            .ok_or("player does not exist")?;
                        let body = data_handle
                            .rigid_body_set
                            .get(module.handle)
                            .ok_or("module rigidbody does not exist")?;

                        let children = module.children.iter().map(|c| {
                            starkingdoms_protocol::module::Attachment {
                                id: c.child,
                                slot: 0,
                                special_fields: SpecialFields::default(),
                            }
                        }).collect();
                        let prot_module = starkingdoms_protocol::module::Module {
                            module_type: module.module_type.into(),
                            rotation: body.rotation().angle(),
                            x: body.translation().x * SCALE,
                            y: body.translation().y * SCALE,
                            id: module_id,
                            flags: module.flags,
                            children,
                            special_fields: SpecialFields::default(),
                        };
                        let msg = MessageS2C::ModuleRemove(MessageS2CModuleRemove {
                            module: Some(prot_module).into(),
                            special_fields: SpecialFields::default(),
                        })
                        .try_into()?;
                        send!(client_tx, msg).await?;
                    }
                    MessageC2S::ModuleGrabBegin(p) => {
                        if let Entity::Module(_module) = entities
                            .write()
                            .await
                            .entities
                            .get_mut(&p.module_id)
                            .ok_or("module does not exist")?
                        {
                            //debug!("[{}] grab begin: {:?}, flags: {}", remote_addr, p, module.flags);
                        }
                    }
                    #[allow(clippy::significant_drop_tightening)]
                    // TODO: Remove when this lint is developed more
                    MessageC2S::ModuleGrabEnd(p) => {
                        let mut entities = entities.write().await;
                        let mut module: Option<Module> = None;
                        let mut did_attach = false;
                        let mut attached_id = None;
                        if let Entity::Module(p_module) = entities
                            .entities
                            .get_mut(&p.module_id)
                            .ok_or("module does not exist")?
                        {
                            module = Some(p_module.clone());
                            //debug!("[{}] grab end: {:?}", remote_addr, p);
                        }
                        let mut data_handle = data.write().await;
                        let player_id = entities
                            .get_player_id(remote_addr)
                            .ok_or("player entity does not exist")?;
                        let player = entities
                            .get_player(remote_addr)
                            .ok_or("player does not exist")?;
                        let body = data_handle
                            .rigid_body_set
                            .get(player.handle)
                            .ok_or("player rigidbody does not exist")?;
                        let (x, y) = (
                            body.translation().x - p.worldpos_x / SCALE,
                            body.translation().y - p.worldpos_y / SCALE,
                        );
                        let angle = -body.rotation().angle();
                        let (x, y) = (
                            x.mul_add(angle.cos(), -y * angle.sin()),
                            x.mul_add(angle.sin(), y * angle.cos()),
                        );
                        let mut attachment_slot: Option<usize> = None;
                        if 1.5 < y && y < 3. && -2. < x && x < 2. {
                            attachment_slot = Some(2);
                        } else if -3. < y && y < -1.5 && -2. < x && x < 2. {
                            attachment_slot = Some(0);
                        } else if -3. < x && x < -1.5 && -2. < y && y < 2. {
                            attachment_slot = Some(3);
                        } else if 1.5 < x && x < 3. && -2. < y && y < 2. {
                            attachment_slot = Some(1);
                        }
                        if let Some(slot) = attachment_slot {
                            attached_id = Some(AttachedModule::attach(
                                &mut data_handle,
                                &mut entities,
                                player_id,
                                player_id,
                                &module.clone().ok_or("module is None")?,
                                slot,
                            ));
                            did_attach = true;
                        }
                        let modules = player.search_modules(&entities);
                        for attached in modules {
                            let body = data_handle
                                .rigid_body_set
                                .get(attached.handle)
                                .ok_or("attached module rigidbody does not exist")?;
                            let (x, y) = (
                                body.translation().x - p.worldpos_x / SCALE,
                                body.translation().y - p.worldpos_y / SCALE,
                            );
                            let angle = -body.rotation().angle();
                            let (x, y) = (
                                x.mul_add(angle.cos(), -y * angle.sin()),
                                x.mul_add(angle.sin(), y * angle.cos()),
                            );
                            let parent_id = entities
                                .get_id_from_attached(&attached)
                                .ok_or("attached module does not exist")?;

                            // ghostly: this is cursed as hell
                            // please find a better way in the future lmao
                            let mut attachment_slot: Option<usize> = None;
                            if 1.5 < y && y < 3. && -2. < x && x < 2. {
                                attachment_slot = Some(2);
                            } else if -3. < x && x < -1.5 && -2. < y && y < 2. {
                                attachment_slot = Some(3);
                            } else if 1.5 < x && x < 3. && -2. < y && y < 2. {
                                attachment_slot = Some(1);
                            }
                            if let Some(slot) = attachment_slot {
                                if let Some(module) = module.clone() {
                                    match attached.module_type {
                                        ModuleType::Cargo => {
                                            continue;
                                        }
                                        ModuleType::LandingThruster => {
                                            continue;
                                        }
                                        ModuleType::LandingThrusterSuspension => {
                                            continue;
                                        }
                                        _ => {}
                                    };
                                    attached_id = Some(AttachedModule::attach(
                                        &mut data_handle,
                                        &mut entities,
                                        parent_id,
                                        player_id,
                                        &module,
                                        slot,
                                    ));
                                    did_attach = true;
                                } else {
                                    return Err("module is None")?;
                                }
                            }
                        }
                        if !did_attach {
                            let body = data_handle
                                .rigid_body_set
                                .get_mut(module.as_ref().ok_or("module does not exist")?.handle)
                                .ok_or("module rigidbody does not exist")?;
                            body.set_position(
                                Isometry::new(
                                    Vector2::new(p.worldpos_x / SCALE, p.worldpos_y / SCALE),
                                    body.rotation().angle(),
                                ),
                                true,
                            );
                            if let Some(module) = module {
                                if module.module_type == ModuleType::LandingThruster {
                                    let suspension = entities.get_module_from_id(module.children.get(0).ok_or("suspension child not found")?.child)
                                        .ok_or("suspension not found")?;
                                    let body = data_handle
                                        .rigid_body_set
                                        .get_mut(suspension.handle)
                                        .ok_or("suspension rigidbody does not exist")?;
                                    body.set_position(
                                        Isometry::new(
                                            Vector2::new(p.worldpos_x / SCALE, p.worldpos_y / SCALE),
                                            body.rotation().angle(),
                                        ),
                                        true,
                                    );
                                }
                            }
                        } else if let Some(Ok(id)) = attached_id {
                            let prot_module = entities
                                .get_attached_from_id(id)
                                .ok_or("attached module does not exist")?
                                .to_protocol(&entities, &data_handle.rigid_body_set);
                            let msg = MessageS2C::ModuleAdd(MessageS2CModuleAdd {
                                module: Some(prot_module.ok_or("attached module does not exist")?)
                                    .into(),
                                special_fields: SpecialFields::default(),
                            })
                            .try_into()?;
                            send!(client_tx, msg).await?;
                        } else {
                            warn!("attached ID does not exist");
                        }
                    }
                },
            }
        }
    }

    Ok(())
}