### GgrsPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsPlugin.html This example demonstrates how to add the GgrsPlugin to a Bevy application, configure rollback frequency, provide input systems, register components for rollback, and start a session. ```APIDOC ## Examples ```rust // Add the GgrsPlugin with your input type app.add_plugins(GgrsPlugin::>::default()); // (optional) Override the default frequency (60) of rollback game logic updates app.insert_resource(RollbackFrameRate(FPS)); // Provide a system to get player input app.add_systems(ReadInputs, read_local_inputs); // Add custom resources/components to be rolled back app.rollback_component_with_clone::(); // Once started, add your Session app.insert_resource(session); ``` ``` -------------------------------- ### Example Usage of RollbackApp Methods Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/rollback_app.rs.html Example demonstrating how to use `rollback_component_with_clone` and `checksum_component_with_hash` to integrate rollback and checksum tracking for components. ```rust app.rollback_component_with_clone::(); app.checksum_component_with_hash::(); ``` -------------------------------- ### Example Usage of GgrsTime Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsTime.html Demonstrates how to access and use the GgrsTime resource within a Bevy system to get the current game time. ```APIDOC ## §Examples ```rust fn get_in_game_time(real_time: Res>, game_time: Res>) { info!("Real Time: {}", real_time.elapsed_secs()); info!("Game Time: {}", game_time.elapsed_secs()); } ``` ``` -------------------------------- ### Plugin::ready Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsPlugin.html Checks if the plugin has finished its setup. This is useful for plugins that require asynchronous operations before they can complete their setup. ```APIDOC ## Plugin::ready ### Description Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. ### Signature ```rust fn ready(&self, _app: &App) -> bool ``` ``` -------------------------------- ### Add ComponentSnapshotPlugin with CloneStrategy Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentSnapshotPlugin.html This example demonstrates how to add the ComponentSnapshotPlugin to a Bevy application, configuring it to use CloneStrategy for the Transform component. This is a common setup for components that can be easily cloned for rollback. ```rust app.add_plugins(ComponentSnapshotPlugin::>::default()); ``` -------------------------------- ### Plugin::finish Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsPlugin.html Completes the plugin's setup after all other registered plugins are ready. This is useful for plugins that depend on the asynchronous setup of other plugins. ```APIDOC ## Plugin::finish ### Description Finish adding this plugin to the `App`, once all plugins registered are ready. This can be useful for plugins that depends on another plugin asynchronous setup, like the renderer. ### Signature ```rust fn finish(&self, _app: &mut App) ``` ``` -------------------------------- ### ComponentSnapshotPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentSnapshotPlugin.html This example demonstrates how to add the ComponentSnapshotPlugin to a Bevy application, configuring it to use a CloneStrategy for the Transform component. ```APIDOC ## Example Usage ```rust // The Transform component is a good candidate for Clone-based rollback app.add_plugins(ComponentSnapshotPlugin::>::default()); ``` ``` -------------------------------- ### Plugin Finish Implementation Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.SnapshotSetPlugin.html Completes the plugin's setup after all registered plugins are ready. This is useful for plugins that depend on the asynchronous setup of other plugins, such as a renderer. ```rust fn finish(&self, _app: &mut App) Finish adding this plugin to the `App`, once all plugins registered are ready. This can be useful for plugins that depends on another plugin asynchronous setup, like the renderer. ``` -------------------------------- ### ResourceSnapshotPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceSnapshotPlugin.html This example demonstrates how to add the ResourceSnapshotPlugin to an Bevy App to enable snapshotting for a custom resource. Ensure the resource derives Clone and is marked with #[derive(Resource)]. ```rust app.add_plugins(ResourceSnapshotPlugin::>::default()); ``` -------------------------------- ### Connect Method Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Demonstrates flattening a slice of strings with a space separator and a slice of integer vectors with a zero separator. ```rust assert_eq!(["hello", "world"].connect(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]); ``` -------------------------------- ### Plugin Ready Check Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.SnapshotSetPlugin.html Checks if the plugin has finished its setup. This is useful for plugins that require asynchronous operations before they can be considered ready. ```rust fn ready(&self, _app: &App) -> bool Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. ``` -------------------------------- ### SnapshotPlugin Setup Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/mod.rs.html Sets up core rollback schedules and systems for Bevy applications. This plugin is independent of the GGRS plugin and can be used in tests or benchmarks. ```rust /// This plugin sets up the [`LoadWorld`], [`SaveWorld`], and [`AdvanceWorld`] /// schedules and adds the required systems and resources for basic rollback /// functionality. /// /// This is independent of the GGRS plugin and can be used with any Bevy app, /// including tests and benchmarks. pub struct SnapshotPlugin; impl Plugin for SnapshotPlugin { /// Registers the rollback schedules, frame-count resources, and core snapshot plugins. fn build(&self, app: &mut App) { app.add_plugins(SnapshotSetPlugin) .init_resource::() .init_resource::() .init_resource::() .init_schedule(LoadWorld) .init_schedule(SaveWorld) .init_schedule(AdvanceWorld) .add_plugins(( EntitySnapshotPlugin, ResourceSnapshotPlugin::>::default(), ChildOfSnapshotPlugin, RollbackDespawnPlugin, )); } } ``` -------------------------------- ### ChecksumPlugin Example Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/checksum.rs.html Demonstrates how to integrate ChecksumPlugin into a Bevy application. It shows how to rollback components and include them in the checksum calculation, and finally adds the ChecksumPlugin to the app. ```rust use bevy::prelude::* use bevy_ggrs::{prelude::*, ChecksumPlugin} const FPS: usize = 60 type MyInputType = u8 fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new() #[derive(Component, Clone, Copy, Hash)] struct Health(u32) // To include something in the checksum, it should also be rolled back app.rollback_component_with_clone::() // This will update the checksum every frame to include Health on rollback entities app.checksum_component_with_hash::() // This will take the Health checksum (and any others) and create a total checksum for the frame app.add_plugins(ChecksumPlugin) } ``` -------------------------------- ### ChecksumPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChecksumPlugin.html This example demonstrates how to use ChecksumPlugin to include custom component data in the checksum. Ensure that components included in the checksum are also rolled back and registered for hashing. ```rust #[derive(Component, Clone, Copy, Hash)] struct Health(u32); // To include something in the checksum, it should also be rolled back app.rollback_component_with_clone::(); // This will update the checksum every frame to include Health on rollback entities app.checksum_component_with_hash::(); // This will take the Health checksum (and any others) and create a total checksum for the frame app.add_plugins(ChecksumPlugin); ``` -------------------------------- ### Plugin finish method for ChildOfSnapshotPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChildOfSnapshotPlugin.html Completes the plugin's setup after all other registered plugins are ready. Useful for plugins that depend on the asynchronous setup of other plugins. ```rust fn finish(&self, _app: &mut App) ``` -------------------------------- ### Plugin ready method for ChildOfSnapshotPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChildOfSnapshotPlugin.html Checks if the plugin has finished its setup. This is useful for plugins that have asynchronous initialization steps. ```rust fn ready(&self, _app: &App) -> bool ``` -------------------------------- ### SessionBuilder::start_synctest_session Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Starts a SyncTestSession for debugging non-determinism. This session simulates rollbacks and compares checksums without network involvement. ```APIDOC ## pub fn start_synctest_session(self) -> Result, GgrsError> ### Description Consumes the builder to construct a new `SyncTestSession`. During a `SyncTestSession`, GGRS simulates a rollback every frame and re-simulates the last `check_distance` frames, then compares checksums against the originals. A mismatch indicates a non-determinism bug in your save/load/advance logic. No network is involved. Checksum comparisons require a `check_distance` of 2 or higher (the default). ### Returns Returns a `SyncTestSession` instance if successful. ### Errors * Returns `InvalidRequest` if `check_distance` is greater than or equal to `max_prediction_window`. * Returns `InvalidRequest` if sparse saving is enabled — synctest must save every frame to compare checksums across the full check window, so sparse saving is incompatible. ``` -------------------------------- ### Example Usage of GgrsTime Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/time.rs.html Demonstrates how to access both real-time and GGRS-synchronized game time within a Bevy system. This is useful for debugging or displaying different time values. ```rust use bevy::prelude::* use bevy_ggrs::prelude::* const FPS: usize = 60; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); app.add_plugins(GgrsPlugin::>::default()); app.add_systems(ReadInputs, read_local_inputs); app.insert_resource(session); fn get_in_game_time(real_time: Res>, game_time: Res>) { info!("Real Time: {}", real_time.elapsed_secs()); info!("Game Time: {}", game_time.elapsed_secs()); } app.add_systems(Update, get_in_game_time); } ``` -------------------------------- ### ImmutableComponentSnapshotPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/component_snapshot.rs.html Demonstrates how to add the ImmutableComponentSnapshotPlugin to a Bevy App for a custom immutable component. ```rust use bevy::prelude::*; use bevy_ggrs::{prelude::*, ImmutableComponentSnapshotPlugin, CloneStrategy}; fn start() { let mut app = App::new(); #[derive(Component, Clone)] #[component(immutable]] struct MyComponent(String); app.add_plugins(ImmutableComponentSnapshotPlugin::>::default()); } ``` -------------------------------- ### ComponentChecksumPlugin Usage Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentChecksumPlugin.html This example demonstrates how to use ComponentChecksumPlugin to track and checksum a custom component. ```APIDOC ## Struct ComponentChecksumPlugin ### Summary ``` pub struct ComponentChecksumPlugin(pub for<'a> fn(&'a C) -> u64); ``` A `Plugin` which will track the `Component` `C` on `Rollback` entities and ensure a `ChecksumPart` is available and updated. This can be used to generate a `Checksum`. ## Examples ```rust #[derive(Component, Clone, Copy, Hash)] struct Health(u32); // To include something in the checksum, it should also be rolled back app.rollback_component_with_clone::(); // This will update the checksum every frame to include Health on rollback entities app.add_plugins(ComponentChecksumPlugin::::default()); ``` ## Tuple Fields §`0: for<'a> fn(&'a C) -> u64` ## Trait Implementations ### impl Default for ComponentChecksumPlugin where C: Component + Hash, #### fn default() -> Self Returns the “default value” for a type. ### impl Plugin for ComponentChecksumPlugin where C: Component, #### fn build(&self, app: &mut App) Registers the checksum update system for this component type in `SaveWorldSystems::Checksum`. #### fn ready(&self, _app: &App) -> bool Has the plugin finished its setup? #### fn finish(&self, _app: &mut App) Finish adding this plugin to the `App`, once all plugins registered are ready. #### fn cleanup(&self, _app: &mut App) Runs after all plugins are built and finished, but before the app schedule is executed. #### fn name(&self) -> &str Configures a name for the `Plugin` which is primarily used for checking plugin uniqueness and debugging. ``` -------------------------------- ### ComponentMapEntitiesPlugin Usage Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentMapEntitiesPlugin.html This example demonstrates how to derive MapEntities for a component and then add the ComponentMapEntitiesPlugin to the Bevy application to enable entity mapping on rollback. ```APIDOC ## ComponentMapEntitiesPlugin A `Plugin` which updates the state of a post-rollback `Component` `C` using `MapEntities`. ### Examples ```rust #[derive(Component, Clone)] struct BestFriend(Entity); impl MapEntities for BestFriend { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped components must be snapshot using any supported method app.rollback_component_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ComponentMapEntitiesPlugin::::default()); ``` ### `impl ComponentMapEntitiesPlugin` #### `pub fn update(world: &mut World)` Exclusive system which will apply a `RollbackEntityMap` to the `Component` `C`, provided it implements `MapEntities`. #### `impl Default for ComponentMapEntitiesPlugin` ##### `fn default() -> Self` Returns the “default value” for a type. ``` -------------------------------- ### Initialize SessionBuilder Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Constructs a new SessionBuilder with default values. This is the starting point for configuring a GGRS session. ```rust pub fn new() -> SessionBuilder ``` -------------------------------- ### Repeat Slice Elements (Panic Example) Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Demonstrates a panic scenario when attempting to repeat a slice with a size that would cause capacity overflow. ```rust // this will panic at runtime b"0123456789abcdef".repeat(usize::MAX); ``` -------------------------------- ### ChecksumPlugin Usage Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChecksumPlugin.html This example demonstrates how to use ChecksumPlugin to include custom component data in the checksum calculation. ```APIDOC ## ChecksumPlugin A `Plugin` which creates a `Checksum` resource which can be read after or during the `SaveWorldSystems::Snapshot` set in the `SaveWorld` schedule has been run. To add you own data to this `Checksum`, create an `Entity` with a `ChecksumPart` `Component`. Every `Entity` with this `Component` will participate in the creation of a `Checksum`. ### Examples ```rust #[derive(Component, Clone, Copy, Hash)] struct Health(u32); // To include something in the checksum, it should also be rolled back app.rollback_component_with_clone::(); // This will update the checksum every frame to include Health on rollback entities app.checksum_component_with_hash::(); // This will take the Health checksum (and any others) and create a total checksum for the frame app.add_plugins(ChecksumPlugin); ``` ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use `iter` to get an iterator that yields immutable references to each element in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### EntitySnapshotPlugin Usage Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.EntitySnapshotPlugin.html This example demonstrates how to add the EntitySnapshotPlugin to a Bevy application. This will ensure entities are updated on rollback to match the state of the target snapshot. ```APIDOC app.add_plugins(EntitySnapshotPlugin); ``` -------------------------------- ### Add ComponentSnapshotPlugin for Transform Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/component_snapshot.rs.html Example of adding `ComponentSnapshotPlugin` for the `Transform` component using `CloneStrategy`. This is useful for components that can be cloned and restored directly. ```rust use bevy::prelude::* use bevy_ggrs::{prelude::*, ComponentSnapshotPlugin, CloneStrategy}; const FPS: usize = 60; type MyInputType = u8; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); // The Transform component is a good candidate for Clone-based rollback app.add_plugins(ComponentSnapshotPlugin::>::default()); } ``` -------------------------------- ### Example: Mapping a Resource with Entity References Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/resource_map.rs.html Demonstrates how to derive `Resource` and implement `MapEntities` for a custom resource, and then register it with `ResourceMapEntitiesPlugin`. This ensures that entity references within the `Player` resource are correctly updated after a rollback. ```rust use bevy::{prelude::*, ecs::entity::{MapEntities, EntityMapper}}; use bevy_ggrs::{prelude::*, ResourceMapEntitiesPlugin}; const FPS: usize = 60; type MyInputType = u8; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); #[derive(Resource, Clone)] struct Player(Entity); impl MapEntities for Player { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped resources must be snapshot using any supported method app.rollback_resource_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ResourceMapEntitiesPlugin::::default()); } ``` -------------------------------- ### RollbackDespawnPlugin Setup Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/despawn.rs.html This plugin registers `RollbackDespawned` as a disabling component and installs systems for entity resurrection during rollback and permanent despawning after frame confirmation. ```rust impl Plugin for RollbackDespawnPlugin { fn build(&self, app: &mut App) { app.register_disabling_component::(); app.add_systems( LoadWorld, resurrect_entities.in_set(LoadWorldSystems::EntityResurrect), ) .add_systems( AdvanceWorld, despawn_confirmed_entities.in_set(AdvanceWorldSystems::DespawnConfirmed), ); } } ``` -------------------------------- ### Get element offset for unaligned element Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Illustrates `element_offset` returning `None` when the provided element reference points to a memory address that is not aligned with the start of an element within the slice. ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Get element offset in a slice Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Finds the index of an element reference within a slice using pointer arithmetic. Returns `None` if the element reference is not aligned with the start of an element in the slice. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Resource Checksum Plugin Example Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/resource_checksum.rs.html Demonstrates how to use `ResourceChecksumPlugin` to include a custom resource in the checksum calculation. Ensure the resource is also rolled back using `rollback_resource_with_clone`. ```rust use bevy::prelude::* use bevy_ggrs::{prelude::*, ResourceChecksumPlugin} const FPS: usize = 60 type MyInputType = u8 fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new() #[derive(Resource, Clone, Hash)] struct BossHealth(u32) // To include something in the checksum, it should also be rolled back app.rollback_resource_with_clone::() // This will update the checksum every frame to include BossHealth app.add_plugins(ResourceChecksumPlugin::::default()) } ``` -------------------------------- ### EntityMapper Get Mapped Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackEntityMap.html Implements the EntityMapper trait to get the target entity for a source entity. ```rust fn get_mapped(&mut self, source: Entity) -> Entity ``` -------------------------------- ### Spawn Player System Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/childof_snapshot.rs.html A simple Bevy system to spawn a player entity. This is often a starting point for systems that manage player-specific entities and their children. ```rust fn spawn_player(mut commands: Commands) { commands.spawn(Player); } ``` -------------------------------- ### Getting the last element of a slice Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use `last` to get an optional reference to the last element of a slice. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Getting the first element of a slice Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use `first` to get an optional reference to the first element of a slice. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Basic Vec Initialization and Assertion Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Demonstrates basic vector initialization and length assertion. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Test: Get absent key returns None Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/rollback_entity_map.rs.html Verifies that calling `get` on a RollbackEntityMap with an entity ID not present in the map correctly returns `None`. ```rust /// get returns None for an entity not in the map. #[test] fn get_absent_key_returns_none() { let m = map_from(&[(1, 2)]); assert_eq!(m.get(entity(99)), None); } ``` -------------------------------- ### ResourceMapEntitiesPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceMapEntitiesPlugin.html Demonstrates how to define a resource that implements MapEntities and how to integrate ResourceMapEntitiesPlugin into a Bevy application. This plugin is essential for resources that need to map entities after a rollback. ```rust #[derive(Resource, Clone)] struct Player(Entity); impl MapEntities for Player { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped resources must be snapshot using any supported method app.rollback_resource_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ResourceMapEntitiesPlugin::::default()); ``` -------------------------------- ### Get Underlying Array Reference - Rust Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Attempts to get a reference to the underlying array if its length matches the specified size `N`. Returns `None` otherwise. ```rust let slice = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); assert!(array_ref.is_some()); let short_array_ref: Option<&[i32; 2]> = slice.as_array(); assert!(short_array_ref.is_none()); ``` -------------------------------- ### ComponentMapEntitiesPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentMapEntitiesPlugin.html Demonstrates how to define a component that maps entities and how to integrate ComponentMapEntitiesPlugin into a Bevy application. Components mapped by this plugin must be registered with `rollback_component_with_clone`. ```rust use bevy::prelude::*; use bevy_ggrs::prelude::*; #[derive(Component, Clone)] struct BestFriend(Entity); impl MapEntities for BestFriend { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped components must be snapshot using any supported method // app.rollback_component_with_clone::(); // This will apply MapEntities on each rollback // app.add_plugins(ComponentMapEntitiesPlugin::::default()); ``` -------------------------------- ### Unsafe Get Mutable Element - Rust Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Get a mutable reference to an element by index without bounds checking. Out-of-bounds access results in undefined behavior. ```rust let x = &mut [1, 2, 4]; unsafe { let elem = x.get_unchecked_mut(1); *elem = 13; } assert_eq!(x, &[1, 13, 4]); ``` -------------------------------- ### System Set Configuration Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/enum.LoadWorldSystems.html Provides methods for configuring system sets, including ordering, conditional execution, and dependency management. ```APIDOC ## impl IntoScheduleConfigs, ()> for S where S: SystemSet, ### Description Provides methods for configuring system sets, including ordering, conditional execution, and dependency management. ### Methods #### `into_configs(self) -> ScheduleConfigs>` Convert into a `ScheduleConfigs`. #### `in_set(self, set: impl SystemSet) -> ScheduleConfigs` Add these systems to the provided `set`. #### `before(self, set: impl IntoSystemSet) -> ScheduleConfigs` Runs before all systems in `set`. If `self` has any systems that produce `Commands` or other `Deferred` operations, all systems in `set` will see their effect. #### `after(self, set: impl IntoSystemSet) -> ScheduleConfigs` Runs after all systems in `set`. If `set` has any systems that produce `Commands` or other `Deferred` operations, all systems in `self` will see their effect. #### `before_ignore_deferred(self, set: impl IntoSystemSet) -> ScheduleConfigs` Runs before all systems in `set`. #### `after_ignore_deferred(self, set: impl IntoSystemSet) -> ScheduleConfigs` Runs after all systems in `set`. #### `distributive_run_if(self, condition: impl SystemCondition + Clone) -> ScheduleConfigs` Add a run condition to each contained system. #### `run_if(self, condition: impl SystemCondition) -> ScheduleConfigs` Run the systems only if the `SystemCondition` is `true`. #### `ambiguous_with(self, set: impl IntoSystemSet) -> ScheduleConfigs` Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with systems in `set`. #### `ambiguous_with_all(self) -> ScheduleConfigs` Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with any other system. #### `chain(self) -> ScheduleConfigs` Treat this collection as a sequence of systems. #### `chain_ignore_deferred(self) -> ScheduleConfigs` Treat this collection as a sequence of systems. ``` -------------------------------- ### Getting a mutable reference to the last element Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use `last_mut` to get an optional mutable reference to the last element of a slice. Returns `None` if the slice is empty. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 5; } assert_eq!(x, &[0, 1, 5]); let y: &mut [i32] = &mut []; assert_eq!(None, y.last_mut()); ``` -------------------------------- ### System Set Configurations Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/enum.LoadWorldSystems.html Methods for configuring system sets, including ordering, conditional execution, and ambiguity resolution. ```APIDOC ### impl IntoScheduleConfigs, ()> for S where S: SystemSet, #### fn into_configs(self) -> ScheduleConfigs> Convert into a `ScheduleConfigs`. #### fn in_set(self, set: impl SystemSet) -> ScheduleConfigs Add these systems to the provided `set`. #### fn before(self, set: impl IntoSystemSet) -> ScheduleConfigs Runs before all systems in `set`. If `self` has any systems that produce `Commands` or other `Deferred` operations, all systems in `set` will see their effect. #### fn after(self, set: impl IntoSystemSet) -> ScheduleConfigs Run after all systems in `set`. If `set` has any systems that produce `Commands` or other `Deferred` operations, all systems in `self` will see their effect. #### fn before_ignore_deferred( self, set: impl IntoSystemSet, ) -> ScheduleConfigs Run before all systems in `set`. #### fn after_ignore_deferred( self, set: impl IntoSystemSet, ) -> ScheduleConfigs Run after all systems in `set`. #### fn distributive_run_if( self, condition: impl SystemCondition + Clone, ) -> ScheduleConfigs Add a run condition to each contained system. #### fn run_if(self, condition: impl SystemCondition) -> ScheduleConfigs Run the systems only if the `SystemCondition` is `true`. #### fn ambiguous_with(self, set: impl IntoSystemSet) -> ScheduleConfigs Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with systems in `set`. #### fn ambiguous_with_all(self) -> ScheduleConfigs Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with any other system. #### fn chain(self) -> ScheduleConfigs Treat this collection as a sequence of systems. #### fn chain_ignore_deferred(self) -> ScheduleConfigs Treat this collection as a sequence of systems. ``` -------------------------------- ### Getting a mutable reference to the first element Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use `first_mut` to get an optional mutable reference to the first element of a slice. Returns `None` if the slice is empty. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); let y: &mut [i32] = &mut []; assert_eq!(None, y.first_mut()); ``` -------------------------------- ### Get Mutable Underlying Array Reference - Rust Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Attempts to get a mutable reference to the underlying array if its length matches `N`. Returns `None` if lengths do not match. ```rust let mut slice = &[1, 2, 3]; let array_mut_ref: Option<&mut [i32; 3]> = slice.as_mut_array(); assert!(array_mut_ref.is_some()); let short_array_mut_ref: Option<&mut [i32; 2]> = slice.as_mut_array(); assert!(short_array_mut_ref.is_none()); ``` -------------------------------- ### Add Bevy GGRS Plugins Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/lib.rs.html Configure the Bevy app to include the GGRS plugin. Ensure input systems are ordered correctly by running after `InputSystems` if in `PreUpdate`. This setup includes necessary checksum and time plugins. ```rust .after(InputSystems), ) .add_plugins((ChecksumPlugin, EntityChecksumPlugin, GgrsTimePlugin)); ``` -------------------------------- ### try_from Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChildOfSnapshotPlugin.html Performs the conversion. ```APIDOC ## fn try_from(value: U) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Register Resource for Rollback with Reflection Strategy Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/rollback_app.rs.html Use this method to register a resource for rollback using the Reflection snapshot strategy. The resource must implement `Reflect` and `FromWorld`. Note that entity mapping is not automatic and may require `ComponentMapEntitiesPlugin`. ```rust fn rollback_resource_with_reflect(&mut self) -> &mut Self where Type: Resource + Reflect + FromWorld; ``` -------------------------------- ### strip_prefix Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> where P: SlicePattern + ?Sized, T: PartialEq, ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - `prefix` (&P) - The prefix to remove. ### Returns - `Option<&[T]>` - A subslice with the prefix removed if it exists, otherwise `None`. ``` -------------------------------- ### Get Vector Length Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns the number of elements currently in the vector. ```rust let mut vec = vec![1, 2, 3]; assert_eq!(vec.len(), 3); ``` -------------------------------- ### CloneToUninit Implementation (Nightly) Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.Checksum.html An experimental nightly-only API for copying data to uninitialized memory. This is an unsafe operation and should be used with extreme caution. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### iter Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns an iterator over the slice, yielding items from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Get Snapshot Storage Capacity Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsSnapshots.html Retrieves the current capacity of the snapshot storage. ```rust pub const fn depth(&self) -> usize ``` -------------------------------- ### Partial Sort Unstable By Key Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Illustrates the usage of `partial_sort_unstable_by_key` with different ranges and a key extraction function based on the absolute value. It shows partitioning and sorting behavior. ```rust #![feature(slice_partial_sort_unstable)] let mut v = [4i32, -5, 1, -3, 2]; // empty range at the beginning, nothing changed v.partial_sort_unstable_by_key(0..0, |k| k.abs()); assert_eq!(v, [4, -5, 1, -3, 2]); // empty range in the middle, partitioning the slice v.partial_sort_unstable_by_key(2..2, |k| k.abs()); for i in 0..2 { assert!(v[i].abs() <= v[2].abs()); } for i in 3..v.len() { assert!(v[2].abs() <= v[i].abs()); } // single element range, same as select_nth_unstable v.partial_sort_unstable_by_key(2..3, |k| k.abs()); for i in 0..2 { assert!(v[i].abs() <= v[2].abs()); } for i in 3..v.len() { assert!(v[2].abs() <= v[i].abs()); } // partial sort a subrange v.partial_sort_unstable_by_key(1..4, |k| k.abs()); assert_eq!(&v[1..4], [2, -3, 4]); // partial sort the whole range, same as sort_unstable v.partial_sort_unstable_by_key(.., |k| k.abs()); assert_eq!(v, [1, 2, -3, 4, -5]); ``` -------------------------------- ### Getting the length of a slice Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use the `len` method to retrieve the number of elements in a slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Implement ResourceSnapshotPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/resource_snapshot.rs.html This implementation registers the snapshot storage and the save/load systems for the specified resource type within the Bevy application. ```rust impl Plugin for ResourceSnapshotPlugin where S: Send + Sync + 'static + Strategy, S::Target: Resource, S::Stored: Send + Sync + 'static, { /// Registers snapshot storage and the save/load systems for this resource type. fn build(&self, app: &mut App) { app.init_resource::>() .add_systems( SaveWorld, ( GgrsResourceSnapshots::::sync_depth, GgrsResourceSnapshots::::discard_old_snapshots, Self::save, ) .chain() .in_set(SaveWorldSystems::Snapshot), ) .add_systems(LoadWorld, Self::load.in_set(LoadWorldSystems::Data)); } } ``` -------------------------------- ### Plugin::build Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsPlugin.html Registers all GGRS resources, schedules, and the session update system within the Bevy application. ```APIDOC ## Plugin::build ### Description Registers all GGRS resources, schedules, and the session update system. ### Signature ```rust fn build(&self, app: &mut App) ``` ``` -------------------------------- ### Get Number of Mappings Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackEntityMap.html Returns the total count of entity mappings stored in the map. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Default Implementation Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackFrameCount.html Provides a default value for RollbackFrameCount, which is typically the starting frame (0). ```APIDOC ### impl Default for RollbackFrameCount #### fn default() -> RollbackFrameCount Returns the “default value” for a type. ``` -------------------------------- ### SnapshotPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.SnapshotPlugin.html This plugin sets up the `LoadWorld`, `SaveWorld`, and `AdvanceWorld` schedules and adds the required systems and resources for basic rollback functionality. This is independent of the GGRS plugin and can be used with any Bevy app, including tests and benchmarks. ```APIDOC ## Struct SnapshotPlugin ```rust pub struct SnapshotPlugin; ``` ### Plugin Implementation #### fn build(&self, app: &mut App) Registers the rollback schedules, frame-count resources, and core snapshot plugins. #### fn ready(&self, _app: &App) -> bool Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. #### fn finish(&self, _app: &mut App) Finish adding this plugin to the `App`, once all plugins registered are ready. This can be useful for plugins that depends on another plugin asynchronous setup, like the renderer. #### fn cleanup(&self, _app: &mut App) Runs after all plugins are built and finished, but before the app schedule is executed. This can be useful if you have some resource that other plugins need during their build step, but after build you want to remove it and send it to another thread. #### fn name(&self) -> &str Configures a name for the `Plugin` which is primarily used for checking plugin uniqueness and debugging. #### fn is_unique(&self) -> bool If the plugin can be meaningfully instantiated several times in an `App`, override this method to return `false`. ``` -------------------------------- ### SessionBuilder::add_player Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Adds a player to the session. This must be called for each player before starting the session. ```APIDOC ## add_player ### Description Must be called for each player in the session (e.g. in a 3 player session, must be called 3 times) before starting the session. Player handles for players should be between 0 and `num_players`, spectator handles should be higher than `num_players`. Later, you will need the player handle to add input, change parameters or disconnect the player or spectator. ### Method ```rust pub fn add_player(self, player_type: PlayerType<::Address>, player_handle: usize) -> Result, GgrsError> ``` ### Errors * Returns `InvalidRequest` if a player with that handle has been added before * Returns `InvalidRequest` if the handle is invalid for the given `PlayerType` ``` -------------------------------- ### CloneToUninit Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/enum.GgrsEvent.html Provides a method to clone data into an uninitialized memory location. This is an experimental, nightly-only API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Safety This function is unsafe because it performs a direct memory copy. The caller must ensure that `dest` is a valid, mutable pointer to enough space to hold `self`, and that `self` is not aliased in a way that would violate memory safety during the copy. ``` -------------------------------- ### SessionBuilder::new Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Constructs a new SessionBuilder with all default values. ```APIDOC ## new() ### Description Construct a new builder with all values set to their defaults. ### Method ```rust pub fn new() -> SessionBuilder ``` ``` -------------------------------- ### Get Entity Mapping Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackEntityMap.html Retrieves the mapped entity for a given entity ID, if a mapping exists. ```rust pub fn get(&self, entity: Entity) -> Option ``` -------------------------------- ### Partial Sort Unstable By Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Demonstrates various use cases of `partial_sort_unstable_by` with different ranges, including empty, single-element, subrange, and full-range sorts. It shows how to use a custom comparison function. ```rust #![feature(slice_partial_sort_unstable)] let mut v = [4, -5, 1, -3, 2]; // empty range at the beginning, nothing changed v.partial_sort_unstable_by(0..0, |a, b| b.cmp(a)); assert_eq!(v, [4, -5, 1, -3, 2]); // empty range in the middle, partitioning the slice v.partial_sort_unstable_by(2..2, |a, b| b.cmp(a)); for i in 0..2 { assert!(v[i] >= v[2]); } for i in 3..v.len() { assert!(v[2] >= v[i]); } // single element range, same as select_nth_unstable v.partial_sort_unstable_by(2..3, |a, b| b.cmp(a)); for i in 0..2 { assert!(v[i] >= v[2]); } for i in 3..v.len() { assert!(v[2] >= v[i]); } // partial sort a subrange v.partial_sort_unstable_by(1..4, |a, b| b.cmp(a)); assert_eq!(&v[1..4], [2, 1, -3]); // partial sort the whole range, same as sort_unstable v.partial_sort_unstable_by(.., |a, b| b.cmp(a)); assert_eq!(v, [4, 2, 1, -3, -5]); ``` -------------------------------- ### Plugin::build Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChildOfSnapshotPlugin.html Registers `ChildOf` snapshot storage and the save/load systems. ```APIDOC ### fn build(&self, app: &mut App) Registers `ChildOf` snapshot storage and the save/load systems. ``` -------------------------------- ### iter_mut Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns an iterator that allows modifying each value in the slice, yielding items from start to end. ```APIDOC ## pub fn iter_mut(&mut self) -> IterMut<'_, T> ### Description Returns an iterator that allows modifying each value. The iterator yields all items from start to end. ### Examples ```rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` ``` -------------------------------- ### as_array Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Gets a reference to the underlying array if the specified size `N` matches the slice's length. ```APIDOC ## as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. ### Details If `N` is not exactly equal to the length of `self`, then this method returns `None`. ``` -------------------------------- ### IntoScheduleConfigs Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/enum.SaveWorldSystems.html Methods for configuring how a set of systems runs within a schedule. ```APIDOC ## impl IntoScheduleConfigs, ()> for S where S: SystemSet, ### into_configs Convert into a `ScheduleConfigs`. ### in_set Add these systems to the provided `set`. ### before Runs before all systems in `set`. If `self` has any systems that produce `Commands` or other `Deferred` operations, all systems in `set` will see their effect. ### after Run after all systems in `set`. If `set` has any systems that produce `Commands` or other `Deferred` operations, all systems in `self` will see their effect. ### before_ignore_deferred Run before all systems in `set`. ### after_ignore_deferred Run after all systems in `set`. ### distributive_run_if Add a run condition to each contained system. ### run_if Run the systems only if the `SystemCondition` is `true`. ### ambiguous_with Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with systems in `set`. ### ambiguous_with_all Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with any other system. ### chain Treat this collection as a sequence of systems. ### chain_ignore_deferred Treat this collection as a sequence of systems. ```