### Basic ECS Setup and System Execution in Rust Source: https://github.com/leudz/shipyard/blob/master/README.md Demonstrates how to define components, add entities with components to a world, and run a system that modifies component data. This is a fundamental example for getting started with Shipyard. ```rust use shipyard::{Component, IntoIter, View, ViewMut, World}; #[derive(Component)] struct Health(u32); #[derive(Component)] struct Position { x: f32, y: f32, } fn in_acid(positions: View, mut healths: ViewMut) { for (_, health) in (&positions, &mut healths) .iter() .filter(|(pos, _)| is_in_acid(pos)) { health.0 -= 1; } } fn is_in_acid(_: &Position) -> bool { // it's wet season true } fn main() { let mut world = World::new(); world.add_entity((Position { x: 0.0, y: 0.0 }, Health(1000))); world.run(in_acid); } ``` -------------------------------- ### Example of a View Bundle Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-further/custom-views.md Demonstrates the structure of a View Bundle, which contains only other views. ```rust struct ViewBundle(ViewA, ViewB); ``` -------------------------------- ### Basic Hierarchy Usage Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/recipes/hierarchy.md Demonstrates the basic usage of creating entities, attaching them to a hierarchy, and then detaching them. ```rust let mut world = World::new(); let mut hierarchy = world.view_mut::<(Parent, Child)>(); let parent = hierarchy.attach_new(EntityId::NONE); let child1 = hierarchy.attach_new(parent); let child2 = hierarchy.attach_new(parent); let grandchild = hierarchy.attach_new(child1); hierarchy.detach(child1); ``` -------------------------------- ### World Setup for Entity Creation Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/fundamentals/add-entity.md This snippet shows the basic world setup required for creating entities in Shipyard. It includes necessary imports and the creation of a world instance. ```rust use shipyard::{World, Entities, View, Component, IntoSystem}; use std::any::Any; struct MyComponent; impl Component for MyComponent {} fn main() { let mut world = World::new(); world.add_entity((MyComponent,)); } ``` -------------------------------- ### Basic Hierarchy Usage Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/recipes/hierarchy.md Demonstrates creating a simple entity hierarchy by attaching new entities to a root. ```rust let mut world = World::new(); let mut hierarchy = Hierarchy::new(&mut world.entities(), &mut world.parents(), &mut world.children()); let root = hierarchy.attach_new(EntityId::NULL); // Root entity let child1 = hierarchy.attach_new(root); let child2 = hierarchy.attach_new(root); let grandchild = hierarchy.attach_new(child1); // Now you have a hierarchy: root -> child1 -> grandchild, root -> child2 ``` -------------------------------- ### Create Systems with Views Source: https://github.com/leudz/shipyard/blob/master/guide/master/src/fundamentals/systems.md Define a system by creating a function that accepts views as arguments. This example shows how to create integer resources. ```rust fn create_ints(mut world: &mut World<()>) { world.insert(Ints(0)); } ``` -------------------------------- ### Create Systems Source: https://github.com/leudz/shipyard/blob/master/guide/0.6/src/fundamentals/systems.md Define a system by creating a function that accepts views as arguments. This example shows how to create integer systems. ```rust fn create_ints() -> Ints { Ints(0) } ``` -------------------------------- ### Game Loop and Win Condition Setup Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/learn-by-example/true-victory.md Sets up the main game loop, including spawning entities and defining win/loss conditions. ```rust use shipyard::{ AllStoragesViewMut, Component, EntitiesView, EntitiesViewMut, IntoIter, IntoWithId, IntoWorkload, IntoWorkloadTrySystem, SparseSet, Unique, UniqueView, UniqueViewMut, View, ViewMut, Workload, World, }; async fn main() { // -- SNIP -- for _ in 0..5 { let _entity_id = world.add_entity(Friend::new()); } world.add_workload(main_loop); loop { clear_background(WHITE); world.run_workload(main_loop); next_frame().await } } #[derive(Debug)] enum GameOver { Defeat, Victory, } impl std::fmt::Display for GameOver { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(self, f) } } impl std::error::Error for GameOver {} fn main_loop() -> Workload { ( move_player, move_friends, grow, counters, spawn, collision, clean_up, check_game_over.into_workload_try_system().unwrap(), render, ) .into_workload() } fn collision( // -- SNIP -- ) { // -- SNIP -- player.square.size -= INIT_SIZE / 2.; player.turn_invincible(); // No more return } else if player.square.size >= friend.0.size && player.square.collide(&friend.0) { // -- SNIP -- } } // No more Ok(()) } fn check_game_over(player: UniqueView, v_friends: View) -> Result<(), GameOver> { if player.square.size < INIT_SIZE { Err(GameOver::Defeat) } else if v_friends.is_empty() { Err(GameOver::Victory) } else { Ok(()) } } ``` -------------------------------- ### Deserialization - Initial Setup Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/recipes/entity-less-serde.md Begin deserialization by handling structs as maps and using `deserialize_in_place` for views that do not own their data. This sets up the structure for deserializing view components. ```rust impl<'a, 'b> DeserializeInPlace for MyView { fn deserialize_in_place<'de, D>(deserializer: D) -> Result<(), D::Error> where D: Deserializer<'de>, { struct MyViewVisitor; impl<'de> Visitor<'de> for MyViewVisitor { type Value = MyView; fn expecting(&self, formatter: &mut std::fmt::Formatter) { formatter.write_str("a struct with vm_name and vm_favorite_language") } fn visit_map(self, mut map: V) -> Result where V: MapAccess<'de>, { let mut vm_name = None; let mut vm_favorite_language = None; while let Some(key) = map.next_key()? { match key { Field::VmName => { if vm_name.is_some() { return Err(serde::de::Error::duplicate_field("vm_name")); } vm_name = Some(map.next_value()?); } Field::VmFavoriteLanguage => { if vm_favorite_language.is_some() { return Err(serde::de::Error::duplicate_field("vm_favorite_language")); } vm_favorite_language = Some(map.next_value()?); } } } let vm_name = vm_name.ok_or_else(|| serde::de::Error::missing_field("vm_name"))?; let vm_favorite_language = vm_favorite_language.ok_or_else(|| serde::de::Error::missing_field("vm_favorite_language"))?; Ok(MyView { vm_name, vm_favorite_language }) } } deserializer.deserialize_struct( "MyView", &["vm_name", "vm_favorite_language"], MyViewVisitor ) } } ``` -------------------------------- ### Basic Hierarchy Usage Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.9/src/recipes/hierarchy.md Demonstrates a simple scenario of creating entities and attaching them to form a basic hierarchy. ```rust let mut world = World::new(); let hierarchy = (world.entities_mut(), world.view_mut(), world.view_mut()); let parent = world.spawn(Parent { num_children: 0, first_child: EntityId::NULL }); let child = world.spawn(Child { parent: EntityId::NULL, prev: EntityId::NULL, next: EntityId::NULL }); hierarchy.attach_new(parent, child); assert_eq!(world.get::(parent).unwrap().num_children, 1); assert_eq!(world.get::(child).unwrap().parent, parent); ``` -------------------------------- ### Example of a Wild View Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-further/custom-views.md Illustrates a Wild View, which can contain views and other types. ```rust struct WildView(ViewA, usize, ViewB); ``` -------------------------------- ### Adding Workloads in Shipyard 0.3 Source: https://github.com/leudz/shipyard/blob/master/guide/0.5.0/src/recipes/0.4-migration.md Example of how workloads were added in Shipyard 0.3 using a tuple of systems. ```rust world.add_workload<(Sys1, Sys2), _>("Workload1"); ``` -------------------------------- ### Hierarchy Test Setup Source: https://github.com/leudz/shipyard/blob/master/guide/0.8/src/recipes/hierarchy.md Sets up a test environment for the hierarchy implementation, including necessary components and trait implementations. ```rust use shipyard::{Component, EntitiesViewMut, EntityId, ViewMut, World}; #[derive(Copy, Clone, Debug, PartialEq)] struct Parent { num_children: u32, first_child: EntityId, } impl Component for Parent {} #[derive(Copy, Clone, Debug, PartialEq)] struct Child { parent: EntityId, prev: EntityId, next: EntityId, } impl Component for Child {} trait Hierarchy { fn detach(&mut self, entity: EntityId); fn attach(&mut self, parent: EntityId, entity: EntityId); fn attach_new(&mut self, parent: EntityId) -> EntityId; } impl Hierarchy for (EntitiesViewMut<'_>, ViewMut<'_, Parent>, ViewMut<'_, Child>) { fn detach(&mut self, entity: EntityId) { let (entities, mut parents, mut children) = self; let child = children.get(entity).unwrap(); let parent = parents.get(child.parent).unwrap(); if parent.first_child == entity { if parent.num_children == 1 { parents.remove(child.parent); } else { parents.get_mut(child.parent).unwrap().first_child = child.next; children.get_mut(child.next).unwrap().prev = child.prev; parents.get_mut(child.parent).unwrap().num_children -= 1; } } else { children.get_mut(child.prev).unwrap().next = child.next; children.get_mut(child.next).unwrap().prev = child.prev; parents.get_mut(child.parent).unwrap().num_children -= 1; } children.remove(entity); } fn attach(&mut self, parent: EntityId, entity: EntityId) { let (entities, mut parents, mut children) = self; let mut parent_mut = parents.get_mut(parent).unwrap(); let first_child = parent_mut.first_child; let num_children = parent_mut.num_children; if num_children == 0 { parents.insert(parent, Parent { num_children: 1, first_child: entity }); children.insert(entity, Child { parent, prev: entity, next: entity }); } else { let first_child_mut = children.get_mut(first_child).unwrap(); let last_child = first_child_mut.prev; children.get_mut(last_child).unwrap().next = entity; children.get_mut(entity).unwrap().prev = last_child; children.get_mut(entity).unwrap().next = first_child; first_child_mut.prev = entity; parent_mut.num_children += 1; } children.get_mut(entity).unwrap().parent = parent; } fn attach_new(&mut self, parent: EntityId) -> EntityId { let entity = self.0.insert((), ()); self.attach(parent, entity); entity } } ``` -------------------------------- ### Create an Integer System Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/fundamentals/systems.md Defines a system that creates integer resources. This is a basic example of system definition. ```rust fn create_ints(world: &mut World) { world.insert(Ints(0)); } ``` -------------------------------- ### View Setup for Entity Management Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/fundamentals/add-entity.md This snippet demonstrates how to set up views in Shipyard, which are essential for querying and managing entities and their components. It shows how to define and use a view. ```rust use shipyard::{World, Entities, View, Component, IntoSystem}; use std::any::Any; struct MyComponent; impl Component for MyComponent {} fn main() { let mut world = World::new(); let entity_id = world.add_entity((MyComponent,)); let mut view = world.view::(); for (_entity, _component) in view.iter() { // Process components } } ``` -------------------------------- ### Shipyard World Creation Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/fundamentals/add-entity.md Demonstrates the basic setup of a Shipyard world, which is the foundation for managing entities and their components. ```rust use shipyard::{World, Entities, View, Component, systems::schedule_once}; struct Position(f32, f32); struct Velocity(f32, f32); fn main() { let mut world = World::new(); world.add_entity((Position(1.0, 2.0), Velocity(0.1, 0.2))); world.add_entity((Position(3.0, 4.0),)); } ``` -------------------------------- ### Basic Hierarchy Usage Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.8/src/recipes/hierarchy.md Demonstrates the basic usage of creating a hierarchy, attaching entities, and traversing them using the implemented methods and iterators. ```rust let mut world = World::new(); let parent = world.insert((), ())[0]; let child = world.insert((), ())[0]; let grandchild = world.insert((), ())[0]; let mut hierarchy = (world.entities(), world.views_mut(), world.views_mut()); hierarchy.attach(parent, child); hierarchy.attach(child, grandchild); let mut children = hierarchy.children_iter(parent); assert_eq!(children.next(), Some(child)); assert_eq!(children.next(), None); let mut ancestors = hierarchy.ancestor_iter(grandchild); assert_eq!(ancestors.next(), Some(child)); assert_eq!(ancestors.next(), Some(parent)); assert_eq!(ancestors.next(), None); let mut descendants = hierarchy.descendant_iter(parent); assert_eq!(descendants.next(), Some(child)); assert_eq!(descendants.next(), Some(grandchild)); assert_eq!(descendants.next(), None); hierarchy.detach(child); let mut children = hierarchy.children_iter(parent); assert_eq!(children.next(), None); let mut ancestors = hierarchy.ancestor_iter(grandchild); assert_eq!(ancestors.next(), None); let mut descendants = hierarchy.descendant_iter(parent); assert_eq!(descendants.next(), None); let mut descendants = hierarchy.descendant_iter(child); assert_eq!(descendants.next(), Some(grandchild)); assert_eq!(descendants.next(), None); hierarchy.attach_new(parent); let mut children = hierarchy.children_iter(parent); assert_eq!(children.next(), Some(grandchild)); assert_eq!(children.next(), Some(world.entities().iter().find(|e| hierarchy.0.get::(*e).map_or(false, |c| c.parent == parent)).unwrap())); assert_eq!(children.next(), None); ``` -------------------------------- ### Original Graphics Frame Setup Source: https://github.com/leudz/shipyard/blob/master/guide/0.8/src/going-further/custom-views.md The original code for setting up a graphics frame within a system, including clearing the screen. ```rust #[derive(Resource)] struct Graphics { device: wgpu::Device, queue: wgpu::Queue, frame: wgpu::SwapChainFrame, view: wgpu::TextureView, } impl Graphics { fn new(window: &winit::window::Window) -> Self { let instance = wgpu::Instance::new(wgpu::Backends::PRIMARY, wgpu::InstanceFlags::default()); let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: None, force_fallback_adapter: false, })) .unwrap(); let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: None, features: wgpu::Features::empty(), limits: wgpu::Limits::default(), })) .unwrap(); let size = window.inner_size(); let swap_chain_descriptor = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: adapter.get_texture_format_ பார்வையாளர்(), width: size.width, height: size.height, present_mode: wgpu::PresentMode::Fifo, }; let swap_chain = device.create_swap_chain(&window.get_surface(), &swap_chain_descriptor); let frame = swap_chain.get_next_texture().unwrap(); let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); Self { device, queue, frame, view } } } struct RenderGraphicsViewMut<'a> { graphics: &'a mut Graphics, } impl<'a> System for RenderGraphicsViewMut<'a> { type Resource = Graphics; fn run(&mut self, mut graphics: Self::Resource) { let color = wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }; let mut render_pass = graphics.device.create_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachment { plate: Some(wgpu::LoadOp::Clear(color)), resolve_target: None, attachment: &graphics.view, }], depth_stencil_attachment: None, }); // Do nothing else drop(render_pass); graphics.queue.submit(std::iter::empty()); graphics.frame.present(); } } ``` -------------------------------- ### Rust Hierarchy Test Setup Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/recipes/hierarchy.md Sets up a test environment with a world and hierarchy components to demonstrate entity attachment and hierarchy traversal. ```rust #[test] fn test_hierarchy() { let world = World::new(); let mut hierarchy = world .borrow::<(EntitiesViewMut, ViewMut, ViewMut)>() .unwrap(); let root1 = hierarchy.0.add_entity((), ()); let root2 = hierarchy.0.add_entity((), ()); let e1 = hierarchy.attach_new(root1); let e2 = hierarchy.attach_new(e1); let e3 = hierarchy.attach_new(e1); let e4 = hierarchy.attach_new(e3); hierarchy.attach(e3, root2); let e5 = hierarchy.attach_new(e3); ``` -------------------------------- ### Sparse Set Insertion Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-deeper/sparse-set.md Demonstrates how entities and their components are inserted into Shipyard's sparse sets. Assumes entity IDs are sequential. ```rust use shipyard::{World, Entities, SparseSet, Component, Schedule, Prelude::*}; #[derive(Clone, Copy, PartialEq, Debug)] struct FirstComponent(i32); #[derive(Clone, Copy, PartialEq, Debug)] struct SecondComponent(i32); fn main() { let mut world = World::new(); let entity_id_0 = world.spawn((FirstComponent(322), SecondComponent(17))); let entity_id_1 = world.spawn((SecondComponent(3154),)); let entity_id_2 = world.spawn((FirstComponent(958), SecondComponent(17))); // Assume entity_id_0 == 0, entity_id_1 == 1, entity_id_2 == 2 // For simplicity, we will use the actual IDs returned by spawn. let first_component_storage: &SparseSet = world.get_storage(); let second_component_storage: &SparseSet = world.get_storage(); println!("SparseSet:"); println!(" sparse: {:?}", first_component_storage.sparse()); println!(" dense: {:?}", first_component_storage.dense()); println!(" data: {:?}", first_component_storage.data()); println!("\nSparseSet:"); println!(" sparse: {:?}", second_component_storage.sparse()); println!(" dense: {:?}", second_component_storage.dense()); println!(" data: {:?}", second_component_storage.data()); } ``` -------------------------------- ### Define a System Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/fundamentals/systems.md A system is a function that takes entity views as arguments. This example shows a basic system signature. ```rust fn create_ints(mut entities: EntitiesViewMut, mut vm_vel: ViewMut) { // -- snip -- } ``` -------------------------------- ### Sparse Set Iteration Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-deeper/sparse-set.md Demonstrates iterating over multiple sparse sets by finding the shortest set and checking for component existence in others. ```rust use shipyard::{World, Entities, SparseSet, Component, Schedule, Prelude::*}; #[derive(Clone, Copy, PartialEq, Debug)] struct FirstComponent(i32); #[derive(Clone, Copy, PartialEq, Debug)] struct SecondComponent(i32); fn main() { let mut world = World::new(); let entity_id_0 = world.spawn((FirstComponent(322), SecondComponent(17))); let entity_id_1 = world.spawn((SecondComponent(3154),)); let entity_id_2 = world.spawn((FirstComponent(958), SecondComponent(17))); // Assume entity_id_0 == 0, entity_id_1 == 1, entity_id_2 == 2 // For simplicity, we will use the actual IDs returned by spawn. let mut query = world.query::<(&FirstComponent, &SecondComponent)>(); let mut entities_with_both = Vec::new(); for (first_comp, second_comp) in query.iter() { entities_with_both.push((first_comp, second_comp)); } println!("Entities with both components:"); for (first, second) in entities_with_both { println!(" {:?}, {:?}", first, second); } } ``` -------------------------------- ### Add and Run Nested Workloads Source: https://github.com/leudz/shipyard/blob/master/guide/0.5.0/src/fundamentals/systems.md This example demonstrates adding a nested workload and then running the parent workload. The systems within the nested workload will execute as defined. ```rust let world = World::new(); Workload::builder("Filter u32") .with_system(&flag_deleted_u32s) .with_system(&clear_deleted_u32s) .add_to_world(&world) .unwrap(); Workload::builder("Loop") .with_system(&increment) .with_workload("Filter u32") .add_to_world(&world) .unwrap(); world.run_workload("Loop").unwrap(); ``` -------------------------------- ### Nested Workload Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/fundamentals/systems.md Illustrates how to nest workloads, allowing for hierarchical organization of system execution logic. This enables building complex execution flows. ```rust let mut workload = Workload::new(); let mut nested = Workload::new(); nested.add_system(create_ints); workload.add_workload(nested); world.add_workload(workload); ``` -------------------------------- ### Define a Basic System Source: https://github.com/leudz/shipyard/blob/master/guide/0.5.0/src/fundamentals/systems.md A system is a function that takes views of entities and components as arguments. This example shows a system that takes mutable views. ```rust fn create_ints(mut entities: EntitiesViewMut, mut u32s: ViewMut) { // -- snip -- } ``` -------------------------------- ### Rust Example Usage of Hierarchy Management Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/recipes/hierarchy.md Demonstrates creating entities, attaching them as children, and moving subtrees within a hierarchy structure using the defined methods. ```rust let world = World::new(); let mut hierarchy = world .borrow::<(EntitiesViewMut, ViewMut, ViewMut)>() .unwrap(); let root1 = hierarchy.0.add_entity((), ()); let root2 = hierarchy.0.add_entity((), ()); let e1 = hierarchy.attach_new(root1); let _e2 = hierarchy.attach_new(e1); let e3 = hierarchy.attach_new(e1); let _e4 = hierarchy.attach_new(e3); hierarchy.attach(e3, root2); ``` -------------------------------- ### Define and Run a Workload Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/fundamentals/systems.md A workload is a group of systems. This example defines a workload containing two systems and then adds and runs it on the world. ```rust fn create_ints(mut entities: EntitiesViewMut, mut vm_vel: ViewMut) { // -- snip -- } fn delete_ints(mut vm_vel: ViewMut) { // -- snip -- } fn int_cycle() -> Workload { (create_ints, delete_ints).into_workload() } let world = World::new(); world.add_workload(int_cycle); world.run_workload(int_cycle).unwrap(); ``` -------------------------------- ### World Initialization and Entity Creation Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/going-deeper/sparse-set.md Initializes a Shipyard World and adds entities with various component combinations. Assumes entity IDs are sequential starting from 0. ```rust let mut world = World::new(); let entity_id_0 = world.add_entity((FirstComponent(322),)); let entity_id_1 = world.add_entity((SecondComponent(17),)); let entity_id_2 = world.add_entity((FirstComponent(5050), SecondComponent(3154))); let entity_id_3 = world.add_entity((FirstComponent(958),)); ``` -------------------------------- ### Manual System Ordering Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-further/visualizer.md This Rust code illustrates manual system ordering using `after_all` and `before_all` functions. It forces specific systems to run between others, modifying the execution constraints without necessarily changing the final outcome. ```rust ( counters, move_player, move_square, grow_square.after_all(move_square).before_all(collision), spawn.after_all(move_square).before_all(collision), collision, clean_up, check_end_floor.into_workload_try_system().unwrap(), render, ) .into_workload() ``` -------------------------------- ### Accessing Components with Get::get Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/fundamentals/get-and-modify.md Use `Get::get` to access components from shared or exclusive views. This method is versatile for retrieving component data. ```rust use shipyard::{*, components::*}; fn get_components(world: &mut World) { world.run(|mut view: ViewMut| { let pos = view.get(EntityId::new(0, 0)); assert!(pos.is_some()); }); world.run(|view: View| { let pos = view.get(EntityId::new(0, 0)); assert!(pos.is_some()); }); } ``` -------------------------------- ### Get Component with Shared and Exclusive Views Source: https://github.com/leudz/shipyard/blob/master/guide/0.9/src/fundamentals/get-and-modify.md Use `Get::get` to access components, compatible with both shared and exclusive entity views. Ensure the necessary traits are in scope. ```rust use shipyard::{*, components::*}; fn get_and_modify(world: &mut World) { let mut query = world.query::<(&mut Position, &mut Velocity)>(); for (mut pos, mut vel) in query.iter_mut() { pos.x += 1.0; vel.x += 1.0; } let mut query = world.query_mut::<(&mut Position, &mut Velocity)>(); for (mut pos, mut vel) in query.iter_mut() { pos.x += 1.0; vel.x += 1.0; } } ``` -------------------------------- ### Basic Workload Builder Source: https://github.com/leudz/shipyard/blob/master/guide/0.6/src/going-deeper/workload-creation.md Demonstrates the initial step of creating a workload with a name and adding a system. ```rust Workload::builder("Add & Check") .with_system(add); ``` -------------------------------- ### Get and Modify Components with Views Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/fundamentals/get-and-modify.md Demonstrates using `Get::get` with mutable views to modify component data for a specific entity. Also shows accessing components via direct indexing on a mutable view. ```rust let mut world = World::new(); let id = world.add_entity((Pos::new(), Vel::new())); world.run(|mut vm_pos: ViewMut, mut vm_vel: ViewMut| { (&mut vm_vel).get(id).unwrap().0 += 1.0; let (mut i, j) = (&mut vm_pos, &vm_vel).get(id).unwrap(); i.0 += j.0; vm_pos[id].0 += 1.0; }); ``` -------------------------------- ### Define a Workload Source: https://github.com/leudz/shipyard/blob/master/guide/0.6/src/fundamentals/systems.md A workload is a collection of systems. This example shows how to define a workload containing systems. ```rust fn workload() -> Workload { // Systems are run first to last and try to run in parallel when possible. // This is called outer-parallelism. Workload::new().with(create_ints, "create_ints").with(run, "run") } ``` -------------------------------- ### Running Systems in Shipyard 0.4 Source: https://github.com/leudz/shipyard/blob/master/guide/0.5.0/src/recipes/0.4-migration.md Demonstrates how to run systems directly using the `run` method on the world in Shipyard 0.4. ```rust world.run(my_system); // and closures still work world.run(|mut entities: EntitiesViewMut, mut usizes: ViewMut| {}); ``` -------------------------------- ### Hierarchy Test Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/recipes/hierarchy.md A comprehensive test case demonstrating hierarchy creation, manipulation, and traversal. ```rust #[test] fn test_hierarchy() { let mut world = World::new(); let mut hierarchy = Hierarchy::new(&mut world.entities(), &mut world.parents(), &mut world.children()); let root = hierarchy.attach_new(EntityId::NULL); let child1 = hierarchy.attach_new(root); let child2 = hierarchy.attach_new(root); let grandchild = hierarchy.attach_new(child1); // Check parent/child relationships assert_eq!(world.children().get(root).unwrap().num_children, 2); assert_eq!(world.children().get(child1).unwrap().num_children, 1); assert_eq!(world.children().get(child2).unwrap().num_children, 0); assert_eq!(world.children().get(grandchild).unwrap().num_children, 0); assert_eq!(world.children().get(child1).unwrap().parent, root); assert_eq!(world.children().get(child2).unwrap().parent, root); assert_eq!(world.children().get(grandchild).unwrap().parent, child1); // Check sibling relationships assert_eq!(world.children().get(child1).unwrap().next, child2); assert_eq!(world.children().get(child2).unwrap().prev, child1); assert_eq!(world.children().get(child1).unwrap().prev, child2); // Circular assert_eq!(world.children().get(child2).unwrap().next, child1); // Circular // Check iterators let mut children = world.parents().children_iter(root); assert_eq!(children.next(), Some(child1)); assert_eq!(children.next(), Some(child2)); assert_eq!(children.next(), None); let mut ancestors = world.parents().ancestor_iter(grandchild); assert_eq!(ancestors.next(), Some(child1)); assert_eq!(ancestors.next(), Some(root)); assert_eq!(ancestors.next(), None); let mut descendants = world.parents().descendant_iter(root); assert_eq!(descendants.next(), Some(child1)); assert_eq!(descendants.next(), Some(grandchild)); assert_eq!(descendants.next(), Some(child2)); assert_eq!(descendants.next(), None); // Detach child1 and its subtree hierarchy.detach(child1); assert_eq!(world.children().get(root).unwrap().num_children, 1); assert_eq!(world.children().get(child1).unwrap().parent, EntityId::NULL); // Detached assert_eq!(world.children().get(grandchild).unwrap().parent, EntityId::NULL); // Detached // Attach child1 to child2 hierarchy.attach(child2, child1); assert_eq!(world.children().get(root).unwrap().num_children, 2); assert_eq!(world.children().get(child1).unwrap().parent, child2); assert_eq!(world.children().get(grandchild).unwrap().parent, child1); // Check sibling relationships after re-attachment assert_eq!(world.children().get(child1).unwrap().next, child2); assert_eq!(world.children().get(child2).unwrap().prev, child1); } ``` ```rust struct Hierarchy<'a> { entities: &'a mut EntitiesViewMut<'a>, parents: ViewMut<'a, Parent>, children: ViewMut<'a, Child>, } impl<'a> Hierarchy<'a> { fn new( entities: &'a mut EntitiesViewMut<'a>, parents: ViewMut<'a, Parent>, children: ViewMut<'a, Child>, ) -> Self { Self { entities, parents, children } } } // Bracket notation for accessing components impl<'a> std::ops::Index for ViewMut<'a, Parent> { type Output = Parent; fn index(&self, entity: EntityId) -> &Self::Output { self.get(entity).unwrap() } } impl<'a> std::ops::IndexMut for ViewMut<'a, Parent> { fn index_mut(&mut self, entity: EntityId) -> &mut Self::Output { self.get_mut(entity).unwrap() } } impl<'a> std::ops::Index for ViewMut<'a, Child> { type Output = Child; fn index(&self, entity: EntityId) -> &Self::Output { self.get(entity).unwrap() } } impl<'a> std::ops::IndexMut for ViewMut<'a, Child> { fn index_mut(&mut self, entity: EntityId) -> &mut Self::Output { self.get_mut(entity).unwrap() } } ``` -------------------------------- ### Run a System Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/fundamentals/systems.md Demonstrates how to execute a defined system using the Shipyard world. This is typically done after defining systems. ```rust let mut world = World::new(); world.add_system(create_ints); world.run(); ``` -------------------------------- ### Initialize World and Add Friends Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/learn-by-example/friends.md Sets up the Shipyard `World`, adds multiple `Friend` entities, and enters the main game loop for rendering and updates. ```rust use macroquad::rand::gen_range; use shipyard::{Component, World}; #[macroquad::main("Square Eater")] async fn main() { rand::srand(macroquad::miniquad::date::now() as u64); // -- SNIP -- let mut world = World::new(); for _ in 0..5 { let _entity_id = world.add_entity(Friend::new()); } loop { clear_background(WHITE); move_player(&mut player); render(&player, &world); next_frame().await } } fn render(player: &Player, world: &World) { for friend in &mut world.iter::<&Friend>() { friend.0.render(GREEN); } player.square.render(BLUE); } impl Friend { fn new() -> Friend { let width = screen_width(); let height = screen_height(); Friend(Square { x: gen_range(0.0, width - 5.0), y: gen_range(0.0, height - 5.0), size: 5.0, }) } } ``` -------------------------------- ### Run a System Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/fundamentals/systems.md After defining a system, you can run it using the World's run method. Ensure the World is initialized. ```rust let world = World::new(); world.run(create_ints); ``` -------------------------------- ### Run Systems Source: https://github.com/leudz/shipyard/blob/master/guide/0.6/src/fundamentals/systems.md Execute a defined system. This snippet demonstrates the basic process of running a system. ```rust fn run(mut world: World) { world.run(create_ints); } ``` -------------------------------- ### Sparse Set Iteration Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.8/src/going-deeper/sparse-set.md Demonstrates iterating over entities that possess a specific component, checking for the presence of other components. ```rust use shipyard::{World, Entities, Component, SparseSet}; #[derive(Clone, Copy, PartialEq, Debug)] struct FirstComponent(i32); #[derive(Clone, Copy, PartialEq, Debug)] struct SecondComponent(i32); let mut world = World::new(); world.add_entity((FirstComponent(322), SecondComponent(17))); world.add_entity((FirstComponent(5050),)); world.add_entity((FirstComponent(958), SecondComponent(3154))); let mut first_component_storage = SparseSet::::new(); let mut second_component_storage = SparseSet::::new(); // Assume entity IDs are in order: 0, 1, 2 // Entity 0 first_component_storage.insert(0, FirstComponent(322)); second_component_storage.insert(0, SecondComponent(17)); // Entity 1 first_component_storage.insert(1, FirstComponent(5050)); // Entity 2 first_component_storage.insert(2, FirstComponent(958)); second_component_storage.insert(2, SecondComponent(3154)); // Iterate over entities that have SecondComponent for entity_id in second_component_storage.iter() { // Check if the entity also has FirstComponent if first_component_storage.contains(entity_id) { // Entity has both components, yield it println!("Entity {} has both components", entity_id); } } // Expected output: // Entity 0 has both components // Entity 2 has both components ``` -------------------------------- ### Implicit System Ordering Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-further/visualizer.md This Rust code demonstrates the implicit ordering of systems based on their definition order in the source code. It shows how systems are assigned to different batches when no manual ordering is specified. ```rust ( counters, move_player, move_square, grow_square, spawn, collision, clean_up, check_end_floor.into_workload_try_system().unwrap(), render, ) .into_workload() ``` -------------------------------- ### Original Frame Creation Code Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-further/custom-views.md The complete initial code for creating a frame, including boilerplate, as presented in the original example. ```rust struct GraphicsComponent { graphics: wgpu::Graphics, output: wgpu::Output, } impl GraphicsComponent { fn new(device: &wgpu::Device, surface: &wgpu::Surface) -> Self { let size = surface.get_preferred_format().unwrap().width; let adapter = device.create_adapter(wgpu::AdapterFlags::default()).unwrap(); let queue = adapter.create_queue(); let texture_size = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1, }; let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, }); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let output = wgpu::Output { texture, view, size, }; GraphicsComponent { graphics: wgpu::Graphics { device: device.into(), queue: queue.into(), }, output, } } } struct RenderGraphicsViewMut<'a> { graphics: &'a mut wgpu::Graphics, output: &'a mut wgpu::Output, } impl<'a> RenderGraphicsViewMut<'a> { fn render(&mut self) { let color = wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }; let mut encoder = self .graphics .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None, }); let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &self.output.view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(color), store: true, }, })], depth_stencil_attachment: None, }); self.graphics.queue.submit(Some(encoder.finish())); } } ``` -------------------------------- ### Initialize Macroquad Window Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/learn-by-example/a-lone-square.md Sets up a blank Macroquad window with the title 'Square Eater'. This is the starting point for any Macroquad application. ```rust use macroquad::prelude::*; #[macroquad::main("Square Eater")] async fn main() { loop { next_frame().await } } ``` -------------------------------- ### Run Systems in Shipyard Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/learn-by-example/spark.md Demonstrates how to execute multiple systems within the Shipyard ECS framework. Systems are functions that operate on world data. ```rust use shipyard::{Component, IntoIter, Unique, UniqueView, UniqueViewMut, View, ViewMut, World}; const GROWTH_RATE: f32 = 0.15; const MAX_SIZE: f32 = 25.0; async fn main() { // -- SNIP -- world.run(move_player); world.run(grow); world.run(render); // -- SNIP -- } ``` -------------------------------- ### Run a System Source: https://github.com/leudz/shipyard/blob/master/guide/0.8/src/fundamentals/systems.md Execute a defined system using the provided code. This snippet demonstrates the basic invocation of a system. ```rust let mut world = World::new(); world.add_system(create_ints); world.run(); ``` -------------------------------- ### Full Hierarchy Test Example Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/recipes/hierarchy.md A comprehensive test case for hierarchy operations, including attachment, detachment, and traversal using iterators. ```rust #[test] fn test_hierarchy() { let mut world = World::new(); let mut hierarchy = world.view_mut::<(Parent, Child)>(); let parent = hierarchy.attach_new(EntityId::NONE); let child1 = hierarchy.attach_new(parent); let child2 = hierarchy.attach_new(parent); let grandchild = hierarchy.attach_new(child1); assert_eq!(hierarchy.get(parent).unwrap().num_children, 2); assert_eq!(hierarchy.get(child1).unwrap().next, child2); assert_eq!(hierarchy.get(child2).unwrap().prev, child1); assert_eq!(hierarchy.get(child1).unwrap().next, grandchild); assert_eq!(hierarchy.get(grandchild).unwrap().prev, child1); let mut children = Vec::new(); for child in hierarchy.children_iter(parent) { children.push(child); } assert_eq!(children, vec![child1, child2]); let mut ancestors = Vec::new(); for ancestor in hierarchy.ancestor_iter(grandchild) { ancestors.push(ancestor); } assert_eq!(ancestors, vec![child1, parent]); let mut descendants = Vec::new(); for descendant in hierarchy.descendant_iter(parent) { descendants.push(descendant); } assert_eq!(descendants, vec![child1, grandchild, child2]); hierarchy.detach(child1); assert_eq!(hierarchy.get(parent).unwrap().num_children, 1); assert_eq!(hierarchy.get(child2).unwrap().prev, child2); assert_eq!(hierarchy.get(child2).unwrap().next, child2); } ``` -------------------------------- ### Create a Shipyard World Source: https://github.com/leudz/shipyard/blob/master/guide/0.6/src/fundamentals/add-entity.md Demonstrates the initialization of a Shipyard world. This is a prerequisite for adding entities. ```rust use shipyard::{World, Entities, View, IntoIter}; use std::any::Any; struct ComponentA(i32); struct ComponentB(i32); fn main() { let mut world = World::default(); ``` -------------------------------- ### Delete Entity from World Source: https://github.com/leudz/shipyard/blob/master/guide/0.9/src/fundamentals/delete-entity.md Use the `commands()` method on the `World` to get a mutable command queue, then call `destroy_entity()` with the entity to delete it and its components. ```rust world.commands().destroy_entity(entity); ``` -------------------------------- ### Entity-less Serialization with Serde Source: https://github.com/leudz/shipyard/blob/master/guide/master/src/recipes/entity-less-serde.md Configure structs for serialization by ignoring `EntitiesViewMut` using `serde(skip)`. This snippet demonstrates the basic setup for serialization. ```rust use serde::{Deserialize, Serialize}; use shipyard::{EntitiesViewMut, ViewMut}; #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)] struct VmName(u32); #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)] struct VmFavoriteLanguage(u32); #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)] struct Vm { #[serde(skip)] entities: EntitiesViewMut<'static>, vm_name: VmName, vm_favorite_language: VmFavoriteLanguage, } ``` -------------------------------- ### Create Systems with Views Source: https://github.com/leudz/shipyard/blob/master/guide/0.8/src/fundamentals/systems.md Define a system by creating a function that accepts views as arguments. This is the fundamental way to structure systems in Shipyard. ```rust fn create_ints(mut query: Query<&mut Int>, mut commands: Commands) { for mut i in query.iter_mut() { i.0 += 1; } commands.spawn((Int(0),) ); } ``` -------------------------------- ### Create a New World Instance Source: https://github.com/leudz/shipyard/blob/master/guide/0.5.0/src/fundamentals/world.md Instantiate the World using either the `default` or `new` methods. Storages are created automatically upon first access, so no explicit registration is needed. ```rust let world = World::default(); let world = World::new(); ``` -------------------------------- ### Manually implement the Component trait Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/fundamentals/world.md Provides an example of manually implementing the `Component` trait for a struct. This is less common than using the derive macro. ```rust struct Position(f32); impl Component for Position {} ``` -------------------------------- ### Rust Hierarchy Test Setup Source: https://github.com/leudz/shipyard/blob/master/guide/0.6/src/recipes/hierarchy.md Sets up a test environment with a World and borrows mutable views for entities, parents, and children to test hierarchy operations. ```rust #[test] fn test_hierarchy() { let world = World::new(); let mut hierarchy = world.borrow::<(EntitiesViewMut, ViewMut, ViewMut)>().unwrap(); let root1 = hierarchy.0.add_entity((), ()); let root2 = hierarchy.0.add_entity((), ()); let e1 = hierarchy.attach_new(root1); let e2 = hierarchy.attach_new(e1); let e3 = hierarchy.attach_new(e1); let e4 = hierarchy.attach_new(e3); hierarchy.attach(e3, root2); let e5 = hierarchy.attach_new(e3); assert!((&hierarchy.1, &hierarchy.2) ``` -------------------------------- ### Custom View Initialization State Struct Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/going-further/custom-views.md Defines a struct to hold the initial state required for a custom view, encapsulating necessary components for setup. ```rust struct InitState { output: Output, graphics: Graphics, } ``` -------------------------------- ### Create Systems with Functions Source: https://github.com/leudz/shipyard/blob/master/guide/0.11/src/fundamentals/systems.md Define systems using functions that accept views as arguments. This is the basic way to create executable logic within Shipyard. ```rust fn create_ints(mut world: &mut World) { world.spawn((1u32, 2u32)); world.spawn((3u32, 4u32)); } ``` -------------------------------- ### Define Basic Components with Derive Source: https://github.com/leudz/shipyard/blob/master/guide/0.7/src/fundamentals/world.md Defines simple components `Pos` and `Vel` using the `Component` derive macro. This snippet is assumed to be present in other examples. ```rust #[derive(Component, Debug)] struct Pos(f32, f32); #[derive(Component, Debug)] struct Vel(f32, f32); ``` -------------------------------- ### Full Custom View Implementation Source: https://github.com/leudz/shipyard/blob/master/guide/0.10/src/going-further/custom-views.md Combines initialization and borrowing logic to create a fully functional custom view, including graphics and output. ```rust struct CustomView { graphics: wgpu::Graphics, output: wgpu::Output, } impl<'a> Borrow for World { fn borrow(&self) -> CustomView { let graphics = wgpu::Graphics::new(); let output = wgpu::Output::new(); CustomView { graphics, output, } } } ```