Skip to content

Commit

Permalink
Merge pull request #151 from cBournhonesque/cb/0.13
Browse files Browse the repository at this point in the history
Cb/0.13
  • Loading branch information
cBournhonesque authored Feb 20, 2024
2 parents 9db4069 + 03f0531 commit 491ff18
Show file tree
Hide file tree
Showing 111 changed files with 1,128 additions and 970 deletions.
8 changes: 8 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,11 @@ rustflags = ["--cfg", "web_sys_unstable_apis"]

[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"

# Enable max optimizations for dependencies, but not for our code:
[profile.dev.package."*"]
opt-level = 3

# Enable only a small amount of optimization in debug mode
[profile.dev]
opt-level = 1
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,9 @@ You can also find more information in this WIP [book](https://cbournhonesque.git
- Examples
- *Lightyear* has plenty of examples demonstrating all these features, as well as the integration with other bevy crates such as `bevy_xpbd_2d`

## Planned features
## Supported bevy version

- Metrics
- Improve the metrics/logs
- Serialization
- Improve the serialization code to be more ergonomic, and to have fewer copies.
- Correctness: add more unit tests for replication edge-cases
| Lightyear | Bevy |
|-----------|------|
| 0.10 | 0.13 |
| 0.9 | 0.12 |
2 changes: 1 addition & 1 deletion benches/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ license = "MIT OR Apache-2.0"
lightyear = { path = "../lightyear" }
crossbeam-channel = "0.5.10"
anyhow = { version = "1.0.75", features = [] }
bevy = { version = "0.12", features = ["bevy_core_pipeline"] }
bevy = { version = "0.13", features = ["bevy_core_pipeline"] }
derive_more = { version = "0.99", features = ["add", "mul"] }
divan = "0.1.11"
serde = { version = "1.0.188", features = ["derive"] }
Expand Down
10 changes: 1 addition & 9 deletions benches/spawn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use bevy::utils::Duration;
use divan::{AllocProfiler, Bencher};
use lightyear::client::sync::SyncConfig;
use lightyear::prelude::client::{InterpolationConfig, PredictionConfig};
use lightyear::prelude::{ClientId, LogConfig, NetworkTarget, SharedConfig, TickConfig};
use lightyear::prelude::{ClientId, NetworkTarget, SharedConfig, TickConfig};
use lightyear_benches::local_stepper::{LocalBevyStepper, Step as LocalStep};
use lightyear_benches::protocol::*;
use lightyear_benches::stepper::{BevyStepper, Step};
Expand All @@ -36,10 +36,6 @@ fn spawn_local(bencher: Bencher, n: usize) {
let tick_duration = Duration::from_millis(10);
let shared_config = SharedConfig {
tick: TickConfig::new(tick_duration),
log: LogConfig {
level: Level::WARN,
..default()
},
..default()
};
let mut stepper = LocalBevyStepper::new(
Expand Down Expand Up @@ -100,10 +96,6 @@ fn spawn(bencher: Bencher, n: usize) {
let tick_duration = Duration::from_millis(10);
let shared_config = SharedConfig {
tick: TickConfig::new(tick_duration),
log: LogConfig {
level: Level::WARN,
..default()
},
..default()
};
let mut stepper = LocalBevyStepper::new(
Expand Down
9 changes: 9 additions & 0 deletions benches/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use bevy::prelude::Component;
use bevy::utils::default;
use derive_more::{Add, Mul};
use serde::{Deserialize, Serialize};
use std::ops::Mul;

use lightyear::prelude::*;

Expand All @@ -22,6 +23,14 @@ pub enum MyMessageProtocol {
#[derive(Component, Message, Serialize, Deserialize, Clone, Debug, PartialEq, Add, Mul)]
pub struct Component1(pub f32);

impl Mul<f32> for &Component1 {
type Output = Component1;

fn mul(self, rhs: f32) -> Self::Output {
Component1(self.0 * rhs)
}
}

#[derive(Component, Message, Serialize, Deserialize, Clone, Debug, PartialEq, Add, Mul)]
pub struct Component2(pub f32);

Expand Down
2 changes: 1 addition & 1 deletion book/src/concepts/advanced_replication/prespawning.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ That's it!

The various system-sets for prespawning are:
- PreUpdate schedule:
- PredictionSet::SpawnPrediction: we first run the prespawn match system to match the pre-spawned entities with their corresponding server entity.
- `PredictionSet::SpawnPrediction`: we first run the prespawn match system to match the pre-spawned entities with their corresponding server entity.
If there is a match, we remove the PreSpawnedPlayerObject component and add the Predicted/Confirmed components.
We then run an apply_deferred, and we run the normal predicted spawn system, which will skip all confirmed entities that
already have a `predicted` counterpart (i.e. were matched)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Currently lightyear only provides option 1: interpolate between the previous tic
## How does it work?

There are 3 main systems:
- during FixedUpdate, we run `update_visual_interpolation_status` after the FixedUpdate::Main set (meaning that the simulation has run).
- during FixedUpdate, we run `update_visual_interpolation_status` after the `FixedUpdate::Main` set (meaning that the simulation has run).
In that system we keep track of the value of the component on the current tick and the previous tick
- during PostUpdate, we run `visual_interpolation` which will interpolate the value of the component between the last two tick values
stored in the `update_visual_interpolation_status` system. We use the `Time<Fixed>::overstep_percentage()` to determine how much to interpolate
Expand Down
3 changes: 1 addition & 2 deletions book/src/tutorial/advanced_systems.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,8 @@ pub(crate) fn movement(
}
}
}
app.add_systems(FixedUpdate, movement.in_set(FixedUpdateSet::Main));
app.add_systems(FixedMain, movement);
```
Don't forget that fixed-timestep simulation systems must run in the `FixedUpdateSet::Main` `SystemSet`.

You might be wondering what the `ComponentSyncMode` is.
This crate specifies 3 different modes for synchronizing components between the `Confirmed` and `Predicted` entities:
Expand Down
4 changes: 2 additions & 2 deletions book/src/tutorial/basic_systems.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,10 @@ pub(crate) fn movement(
}
}
}
app.add_systems(FixedUpdate, movement.in_set(FixedUpdateSet::Main));
app.add_systems(FixedMain, movement);
```

Any fixed-update simulation system (physics, etc.) must run in the `FixedUpdateSet::Main` `SystemSet` to behave correctly.
Any fixed-update simulation system (physics, etc.) must run in the `FixedMain` `Schedule` to behave correctly.

## Displaying entities

Expand Down
10 changes: 5 additions & 5 deletions examples/bullet_prespawn/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ metrics = ["lightyear/metrics", "dep:metrics-exporter-prometheus"]
mock_time = ["lightyear/mock_time"]

[dependencies]
bevy_framepace = "0.14.1"
bevy_screen_diagnostics = "0.4.0"
leafwing-input-manager = "0.11.2"
bevy_framepace = "0.15"
bevy_screen_diagnostics = "0.5.0"
leafwing-input-manager = "0.13"
lightyear = { path = "../../lightyear", features = [
"webtransport",
"websocket",
Expand All @@ -25,11 +25,11 @@ serde = { version = "1.0.188", features = ["derive"] }
anyhow = { version = "1.0.75", features = [] }
tracing = "0.1"
tracing-subscriber = "0.3.17"
bevy = { version = "0.12", features = ["bevy_core_pipeline"] }
bevy = { version = "0.13", features = ["bevy_core_pipeline"] }
derive_more = { version = "0.99", features = ["add", "mul"] }
rand = "0.8.1"
clap = { version = "4.4", features = ["derive"] }
mock_instant = "0.3"
metrics-exporter-prometheus = { version = "0.13.0", optional = true }
bevy-inspector-egui = "0.22.1"
#bevy-inspector-egui = "0.22.1"
cfg-if = "1.0.0"
29 changes: 14 additions & 15 deletions examples/bullet_prespawn/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use bevy::app::PluginGroupBuilder;
use bevy::ecs::schedule::{LogLevel, ScheduleBuildSettings};
use bevy::prelude::*;
use bevy::utils::Duration;
use leafwing_input_manager::action_state::ActionDiff;
use leafwing_input_manager::action_state::ActionData;
use leafwing_input_manager::axislike::DualAxisData;
use leafwing_input_manager::buttonlike::ButtonState::Pressed;
use leafwing_input_manager::orientation::Orientation;
Expand Down Expand Up @@ -93,7 +93,7 @@ impl PluginGroup for ClientPluginGroup {
.add(shared::SharedPlugin)
.add(LeafwingInputPlugin::<MyProtocol, PlayerActions>::new(
LeafwingInputConfig::<PlayerActions> {
send_diffs_only: false,
send_diffs_only: true,
..default()
},
))
Expand All @@ -120,16 +120,16 @@ impl Plugin for ExampleClientPlugin {
// To send global inputs, insert the ActionState and the InputMap as Resources
app.init_resource::<ActionState<AdminActions>>();
app.insert_resource(InputMap::<AdminActions>::new([
(KeyCode::M, AdminActions::SendMessage),
(KeyCode::R, AdminActions::Reset),
(AdminActions::SendMessage, KeyCode::KeyM),
(AdminActions::Reset, KeyCode::KeyR),
]));

app.insert_resource(ClientIdResource {
client_id: self.client_id,
});
app.add_systems(Startup, init);
// all actions related-system that can be rolled back should be in FixedUpdateSet::Main
// app.add_systems(FixedUpdate, player_movement.in_set(FixedUpdateSet::Main));
// all actions related-system that can be rolled back should be in the `FixedUpdate` schdule
// app.add_systems(FixedUpdate, player_movement);
// we update the ActionState manually from cursor, so we need to put it in the ManualControl set
app.add_systems(
PreUpdate,
Expand Down Expand Up @@ -162,11 +162,11 @@ pub(crate) fn init(mut commands: Commands, mut client: ClientMut, plugin: Res<Cl
Vec2::new(-50.0, y),
color_from_id(plugin.client_id),
InputMap::new([
(KeyCode::W, PlayerActions::Up),
(KeyCode::S, PlayerActions::Down),
(KeyCode::A, PlayerActions::Left),
(KeyCode::D, PlayerActions::Right),
(KeyCode::Space, PlayerActions::Shoot),
(PlayerActions::Up, KeyCode::KeyW),
(PlayerActions::Down, KeyCode::KeyS),
(PlayerActions::Left, KeyCode::KeyA),
(PlayerActions::Right, KeyCode::KeyD),
(PlayerActions::Shoot, KeyCode::Space),
]),
));
let _ = client.connect();
Expand All @@ -180,12 +180,11 @@ fn update_cursor_state_from_window(
for window in window_query.iter() {
for mut action_state in action_state_query.iter_mut() {
if let Some(val) = window_relative_mouse_position(window) {
action_state.press(&PlayerActions::MoveCursor);
action_state
.action_data_mut(PlayerActions::MoveCursor)
.action_data_mut(&PlayerActions::MoveCursor)
.unwrap()
.axis_pair = Some(DualAxisData::from_xy(val));
action_state
.action_data_mut(PlayerActions::MoveCursor)
.state = Pressed;
}
}
}
Expand Down
16 changes: 11 additions & 5 deletions examples/bullet_prespawn/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use bevy::log::{Level, LogPlugin};
use bevy::prelude::*;
use bevy::tasks::IoTaskPool;
use bevy::DefaultPlugins;
use bevy_inspector_egui::quick::WorldInspectorPlugin;
// use bevy_inspector_egui::quick::WorldInspectorPlugin;
use clap::{Parser, ValueEnum};
use serde::{Deserialize, Serialize};

Expand All @@ -28,6 +28,7 @@ use crate::client::ClientPluginGroup;
use crate::server::ServerPluginGroup;
use lightyear::connection::netcode::{ClientId, Key};
use lightyear::prelude::TransportConfig;
use lightyear::shared::log::add_log_layer;

// Use a port of 0 to automatically select a port
pub const CLIENT_PORT: u16 = 0;
Expand Down Expand Up @@ -132,13 +133,17 @@ fn setup(app: &mut App, cli: Cli) {
predict,
} => {
if !headless {
app.add_plugins(DefaultPlugins.build().disable::<LogPlugin>());
app.add_plugins(DefaultPlugins.build().set(LogPlugin {
level: Level::INFO,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
update_subscriber: Some(add_log_layer),
}));
} else {
app.add_plugins(MinimalPlugins);
}

if inspector {
app.add_plugins(WorldInspectorPlugin::new());
// app.add_plugins(WorldInspectorPlugin::new());
}
// this is async because we need to load the certificate from io
// we need async_compat because wtransport expects a tokio reactor
Expand Down Expand Up @@ -173,12 +178,13 @@ fn setup_client(app: &mut App, cli: Cli) {
// NOTE: create the default plugins first so that the async task pools are initialized
// use the default bevy logger for now
// (the lightyear logger doesn't handle wasm)
app.add_plugins(DefaultPlugins.set(LogPlugin {
app.add_plugins(DefaultPlugins.build().set(LogPlugin {
level: Level::INFO,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
update_subscriber: Some(add_log_layer),
}));
if inspector {
app.add_plugins(WorldInspectorPlugin::new());
// app.add_plugins(WorldInspectorPlugin::new());
}
let server_addr = SocketAddr::new(server_addr.into(), server_port);
let client_plugin_group =
Expand Down
1 change: 0 additions & 1 deletion examples/bullet_prespawn/src/protocol.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use bevy::prelude::*;
use bevy::utils::EntityHashSet;
use derive_more::{Add, Mul};
use leafwing_input_manager::prelude::*;
use lightyear::client::components::LerpFn;
Expand Down
13 changes: 5 additions & 8 deletions examples/bullet_prespawn/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,8 @@ impl ServerPluginGroup {
Certificate::load("../certificates/cert.pem", "../certificates/key.pem")
.await
.unwrap();
let digest = certificate.hashes()[0].fmt_as_dotted_hex();
dbg!(
"Generated self-signed certificate with digest: {:?}",
digest
);
let digest = &certificate.hashes()[0];
println!("Generated self-signed certificate with digest: {}", digest);
TransportConfig::WebTransportServer {
server_addr,
certificate,
Expand Down Expand Up @@ -87,10 +84,10 @@ impl Plugin for ExampleServerPlugin {
// Re-adding Replicate components to client-replicated entities must be done in this set for proper handling.
app.add_systems(
PreUpdate,
(replicate_players).in_set(MainSet::ClientReplication),
replicate_players.in_set(MainSet::ClientReplication),
);
// the physics/FixedUpdates systems that consume inputs should be run in this set
// app.add_systems(FixedUpdate, (player_movement).in_set(FixedUpdateSet::Main));
// the physics/FixedUpdates systems that consume inputs should be run in the `FixedUpdate` schedule
// app.add_systems(FixedUpdate, player_movement);
app.add_systems(Update, handle_disconnections);
}
}
Expand Down
Loading

0 comments on commit 491ff18

Please sign in to comment.