Commit graph

9 commits

Author SHA1 Message Date
Ryan Johnson 11ba70586e
Decoupled Packet Handlers (#315)
## Description

Closes #296 

- Redesigned the packet decoder to return packet _frames_ which are just
the packet ID + data in raw form.
- Made packet frame decoding happen in the client's tokio task. This has
a few advantages:
- Packet frame decoding (decompression + decryption + more) can happen
in parallel.
- Because packets are parsed as soon as they arrive, an accurate
timestamp can be included with the packet. This enables us to implement
client ping calculation accurately.
- `PacketEvent`s are now sent in the event loop instead of a giant match
on the serverbound packets. This is good because:
- Packets can now be handled from completely decoupled systems by
reading `PacketEvent` events.
- The entire packet is available in binary form to users, so we don't
need to worry about losing information when transforming packets to
events. I.e. an escape hatch is always available.
  - The separate packet handlers can run in parallel thanks to bevy_ecs.
- The inventory packet handler systems have been unified and moved
completely to the inventory module. This also fixed some issues where
certain inventory events could _only_ be handled one tick late.
- Reorganized the client module and moved things into submodules.
- The "default event handler" has been removed in favor of making
clients a superset of `PlayerEntityBundle`. It is no longer necessary to
insert `PlayerEntityBundle` when clients join. This does mean you can't
insert other entity types on the client, but that design doesn't work
for a variety of reasons. We will need an "entity visibility" system
later anyway.

## Test Plan

Steps:
1. Run examples and tests.
2023-04-08 19:55:31 +00:00
Ryan Johnson 9c9f672a22
Update to 1.19.4 (#302)
## Description

Closes #291

- Update extractors to support Minecraft 1.19.4
- Update code generators.
- Changed generated entity component names to avoid name collisions.
- Update `glam` version.
- Added `Encode` and `Decode` for `glam` types in `valence_protocol`.
- Fixed inconsistent packet names and assign packet IDs automatically.
- Remove `ident` and rename `ident_str` to `ident`.
- Rework registry codec configuration. Biomes and dimensions exist as
entities.`BiomeRegistry` and `DimensionTypeRegistry` resources have been
added. The vanilla registry codec is loaded at startup.

### Issues
- Creating new instances has become more tedious than it should be. This
will be addressed later.

## Test Plan

Steps:
1. Boot up a vanilla server with online mode disabled.
2. Run the `packet_inspector`.
3. Connect to the vanilla server through the packet inspector to ensure
all packets are updated correctly.
4. Close the vanilla server and try some valence examples.
2023-03-31 14:58:47 -07:00
Ryan Johnson 4cf6e1a207
Entity Rework (#294)
## Description

Closes #269
Closes #199 

- Removes `McEntity` and replaces it with bundles of components, one for
each entity type.
- Tracked data types are now separate components rather than stuffing
everything into a `TrackedData` enum.
- Tracked data is now cached in binary form within each entity,
eliminating some work when entities enter the view of clients.
- Complete redesign of entity code generator.
- More docs for some components.
- Field bits are moved out of the entity extractor and into the valence
entity module.
- Moved hitbox code to separate module.
- Refactor instance update systems to improve parallelism.

### TODOs
- [x] Update examples.
- [x] Update `default_event_handler`.
- [x] Fix bugs.

## Test Plan

Steps:
1. Check out the entity module docs with `cargo d --open`.
2. Run examples.
2023-03-21 23:29:38 -07:00
Ryan Johnson b46cc502aa
Client Component Division (#266)
## Description

Divides the `Client` component into a set of smaller components as
described by #199 (with many deviations). `McEntity` will be dealt with
in a future PR.

- Divide `Client` into smaller components (There's a lot to look at).
- Move common components to `component` module.
- Remove `Username` type from `valence_protocol` because the added
complexity wasn't adding much benefit.
- Clean up the inventory module.

I've stopped worrying about the "Effect When Added" and "Effect When
Removed" behavior of components so much, and instead assume that all
components of a particular thing are required unless otherwise stated.

## Test Plan

Steps:
1. Run examples and tests.

A large number of tweaks have been made to the inventory module. I tried
to preserve semantics but I could have made a mistake there.

---------

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
Co-authored-by: Carson McManus <carson.mcmanus1@gmail.com>
2023-03-11 06:04:14 -08:00
Ryan Johnson 62f882eec7
Update to Bevy 0.10 (#265)
## Description

Fix #264

Bevy version is pinned to a recent commit on the main branch until 0.10
is released.

## Test Plan

Run examples and tests. Behavior should be the same.

scheduling is a bit tricky so I may have made some subtle mistakes.
2023-03-04 03:35:11 -08:00
Supermath101 cc2571d7e6
Changed setup() to not be an exclusive system (#258)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

In the [examples of the `valence`
crate](https://github.com/valence-rs/valence/tree/main/crates/valence/examples),
the `setup()` functions are currently [exclusive
systems](https://bevy-cheatbook.github.io/programming/exclusive.html).
My reasoning for making these a standard system is twofold:
- Exclusive systems can be considered an advanced Bevy topic. I don't
think you should be using advanced concepts in examples meant to be an
introduction to the way this project/framework is used.
- In instances where developers try to use these examples, adding
another startup system would result is running the systems sequentially.
That leaves performance on the table (albeit only during startup).

---------

Co-authored-by: Supermath101 <unknown>
Co-authored-by: Supermath101 <>
2023-02-27 12:13:56 -08:00
Carson McManus 0319635a8b
Implement Drop Item Events (#252)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->
Dropping items is heavily coupled to inventories. Clients also predict
state changes when they try to drop items, so we need to be able to
replicate that change in order to stay in sync.

This will also remove `DropItem` events in favor of just `DropItemStack`
events. Having 2 event streams that basically mean the same thing seems
verbose and error prone.

As of right now, these changes require the event loop to have a
reference to the client's inventory. This seems like something we are
going to need to do a lot more of to complete #199.

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

<details>

<summary>Playground</summary>

```rust
use tracing::info;
use valence::client::despawn_disconnected_clients;
use valence::client::event::{default_event_handler, DropItemStack};
use valence::prelude::*;

#[allow(unused_imports)]
use crate::extras::*;

const SPAWN_Y: i32 = 64;

pub fn build_app(app: &mut App) {
    app.add_plugin(ServerPlugin::new(()).with_connection_mode(ConnectionMode::Offline))
        .add_system_to_stage(EventLoop, default_event_handler)
        .add_startup_system(setup)
        .add_system(init_clients)
        .add_system(despawn_disconnected_clients)
        .add_system(toggle_gamemode_on_sneak)
        .add_system(drop_items);
}

fn setup(world: &mut World) {
    let mut instance = world
        .resource::<Server>()
        .new_instance(DimensionId::default());

    for z in -5..5 {
        for x in -5..5 {
            instance.insert_chunk([x, z], Chunk::default());
        }
    }

    for z in -25..25 {
        for x in -25..25 {
            instance.set_block([x, SPAWN_Y, z], BlockState::GRASS_BLOCK);
        }
    }

    world.spawn(instance);
}

fn init_clients(
    mut clients: Query<&mut Client, Added<Client>>,
    instances: Query<Entity, With<Instance>>,
) {
    let instance = instances.get_single().unwrap();

    for mut client in &mut clients {
        client.set_position([0.5, SPAWN_Y as f64 + 1.0, 0.5]);
        client.set_instance(instance);
        client.set_game_mode(GameMode::Creative);
    }
}

fn drop_items(clients: Query<&Client>, mut drop_stack_events: EventReader<DropItemStack>) {
    if drop_stack_events.is_empty() {
        return;
    }

    for event in drop_stack_events.iter() {
        info!("drop stack: {:?}", event);
    }
}

```

</details>

<!-- You need to include steps regardless of whether or not you are
using a playground. -->
Steps:
1. `cargo test -p valence --tests`
2. Run playground `cargo run -p playground`
3. Open creative menu
4. Pick an item and click to drop it outside of the creative menu
5. Pick an entire stack of an item, place it in your hotbar
6. Hover over the item, press your drop key to drop an item from the
stack
7. Press shift to switch to survival
8. Select the item stack in your hotbar, press your drop key to drop an
item from the stack
9. Open your inventory, grab the stack, hover outside the window and
click to drop the entire stack
10. Grab another stack from creative, place it in your hotbar
11. switch back to survival, select the stack, and press your control +
drop key to drop the entire stack
12. For each item you dropped, you should see a log message with the
event

#### Related

<!-- Link to any issues that have context for this or that this PR
fixes. -->
2023-02-20 15:37:09 -08:00
Mrln 1ceafe0ce0
Add block entities (#32)
This PR aims to add block entities.
Fixes #5

---------

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2023-02-18 10:16:01 -08:00
Ryan Johnson cb9230ec34
ECS Rewrite (#184)
This PR redesigns Valence's architecture around the Bevy Entity
Component System framework (`bevy_ecs` and `bevy_app`). Along the way, a
large number of changes and improvements have been made.
- Valence is now a Bevy plugin. This allows Valence to integrate with
the wider Bevy ecosystem.
- The `Config` trait has been replaced with the plugin struct which is
much easier to configure. Async callbacks are grouped into their own
trait.
- `World` has been renamed to `Instance` to avoid confusion with
`bevy_ecs::world::World`.
- Entities, clients, player list, and inventories are all just ECS
components/resources. There is no need for us to have our own
generational arena/slotmap/etc for each one.
- Client events use Bevy's event system. Users can read events with the
`EventReader` system parameter. This also means that events are
dispatched at an earlier stage of the program where access to the full
server is available. There is a special "event loop" stage which is used
primarily to avoid the loss of ordering information between events.
- Chunks have been completely overhauled to be simpler and faster. The
distinction between loaded and unloaded chunks has been mostly
eliminated. The per-section bitset that tracked changes has been
removed, which should further reduce memory usage. More operations on
chunks are available such as removal and cloning.
- The full client's game profile is accessible rather than just the
textures.
- Replaced `vek` with `glam` for parity with Bevy.
- Basic inventory support has been added.
- Various small changes to `valence_protocol`.
- New Examples
- The terrain and anvil examples are now fully asynchronous and will not
block the main tick loop while chunks are loading.

# TODOs
- [x] Implement and dispatch client events.
- ~~[ ] Finish implementing the new entity/chunk update algorithm.~~ New
approach ended up being slower. And also broken.
- [x] [Update rust-mc-bot to
1.19.3](https://github.com/Eoghanmc22/rust-mc-bot/pull/3).
- [x] Use rust-mc-bot to test for and fix any performance regressions.
Revert to old entity/chunk update algorithm if the new one turns out to
be slower for some reason.
- [x] Make inventories an ECS component.
- [x] Make player lists an ECS ~~component~~ resource.
- [x] Expose all properties of the client's game profile.
- [x] Update the examples.
- [x] Update `valence_anvil`.
- ~~[ ] Update `valence_spatial_index` to use `glam` instead of `vek`.~~
Maybe later
- [x] Make entity events use a bitset.
- [x] Update docs.

Closes #69
Closes #179
Closes #53

---------

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
Co-authored-by: AviiNL <me@avii.nl>
Co-authored-by: Danik Vitek <x3665107@gmail.com>
Co-authored-by: Snowiiii <71594357+Snowiiii@users.noreply.github.com>
2023-02-11 09:51:53 -08:00