|
| 1 | +use bevy_ecs::prelude::*; |
| 2 | +use ferrumc_core::identity::player_identity::PlayerIdentity; |
| 3 | +use ferrumc_core::transform::position::Position; |
| 4 | +use ferrumc_core::transform::rotation::Rotation; |
| 5 | +use ferrumc_entities::components::*; // Includes SyncedToPlayers |
| 6 | +use ferrumc_entities::types::passive::pig::EntityUuid; |
| 7 | +use ferrumc_net::connection::StreamWriter; |
| 8 | +use ferrumc_net::packets::outgoing::spawn_entity::SpawnEntityPacket; |
| 9 | +use tracing::{debug, error}; |
| 10 | + |
| 11 | +/// System that send new entities to players |
| 12 | +pub fn entity_sync_system( |
| 13 | + // All non-player entities they needed to be sync |
| 14 | + mut entity_query: Query< |
| 15 | + ( |
| 16 | + Entity, |
| 17 | + &EntityType, |
| 18 | + &EntityId, |
| 19 | + &EntityUuid, |
| 20 | + &Position, |
| 21 | + &Rotation, |
| 22 | + &mut SyncedToPlayers, |
| 23 | + ), |
| 24 | + Without<PlayerIdentity>, |
| 25 | + >, |
| 26 | + |
| 27 | + // All connected players |
| 28 | + player_query: Query<(Entity, &StreamWriter, &Position), With<PlayerIdentity>>, |
| 29 | +) { |
| 30 | + for (entity, entity_type, entity_id, entity_uuid, pos, rot, mut synced) in |
| 31 | + entity_query.iter_mut() |
| 32 | + { |
| 33 | + for (player_entity, stream_writer, player_pos) in player_query.iter() { |
| 34 | + // Skip if already send to the player |
| 35 | + if synced.player_entities.contains(&player_entity) { |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + // TODO: Check distance (render distance) |
| 40 | + let distance = ((pos.x - player_pos.x).powi(2) + (pos.z - player_pos.z).powi(2)).sqrt(); |
| 41 | + |
| 42 | + if distance > 128.0 { |
| 43 | + // 8 chunks de distance |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + // Create and send spawn packet |
| 48 | + let protocol_id = entity_type.protocol_id(); |
| 49 | + debug!( |
| 50 | + "Spawning {:?} (protocol_id={}) at ({:.2}, {:.2}, {:.2}) for player {:?}", |
| 51 | + entity_type, protocol_id, pos.x, pos.y, pos.z, player_entity |
| 52 | + ); |
| 53 | + |
| 54 | + let spawn_packet = SpawnEntityPacket::entity( |
| 55 | + entity_id.0, |
| 56 | + entity_uuid.0.as_u128(), |
| 57 | + protocol_id, |
| 58 | + pos, |
| 59 | + rot, |
| 60 | + ); |
| 61 | + |
| 62 | + if let Err(e) = stream_writer.send_packet(spawn_packet) { |
| 63 | + error!("Failed to send spawn packet: {:?}", e); |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + // TODO: Send EntityMetadataPacket here to properly display the entity |
| 68 | + // The EntityMetadata constructors are not publicly exported yet |
| 69 | + // This might be why the pig appears as a phantom! |
| 70 | + |
| 71 | + synced.player_entities.push(player_entity); |
| 72 | + debug!( |
| 73 | + "Successfully sent entity {:?} (ID: {}) to player {:?}", |
| 74 | + entity, entity_id.0, player_entity |
| 75 | + ); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments