Skip to content

Improve the ClientId ergonomics for listen servers #688

Description

@malfuu

I wanted to propose adding the server as a client entity, a feature that would reduce listen-server exclusive code.

My change would be turning ClientId into:

pub enum ClientId {
    Client(Entity),
    Server(Entity),
}

Allowing for entity() to change into:

impl ClientId {
    pub fn entity(self) -> Entity {
        match self {
            ClientId::Client(entity) => entity,
            ClientId::Server(entity) => entity,
        }
    }
}

This could also reduce boilerplate when retrieving player information, where as before:

#[derive(Event)]
struct PrintPlayerName;

fn print_name(
    event: On<FromClient<PrintPlayerName>>,
    players: Query<&Name>,
    server_player: Local<Entity> // assume it is correctly initialized
) {
    // long chain to obtain a player entity (and even then its assuming ServerEntity always exists)
    let player_entity = event.client_id.entity().unwrap_or(**server_player);

    info!("{}", players.get(player_entity).unwrap());
}

Can be turned into:

fn print_name(
    event: On<FromClient<PrintPlayerName>>,
    players: Query<&Name>,
) {
    let player_entity = event.client_id.entity(); // using the new impl of entity()

    info!("{}", players.get(player_entity).unwrap());
}

I could see this being more useful in:

  • Reducing boilerplate where per-player components/relationships matter
  • Visibility rules being applied in the listen server instance (instead of despawning entities, Visibility is togggled)

Although, this would impose a requirement to the backend to provide its client entity for the server instance, I think it is a fair price to pay for listen-servers. I wanted to know what you think of this idea, because we can both agree it will sacrifice the ergonomics for dedicated servers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions