#![feature(test)] extern crate test; #[macro_use] extern crate trex; use trex::{FamilyMember, System, EventQueue, EventEmitter, Simulation, World, ComponentFilter}; use test::Bencher; pub const N_POS_VEL: usize = 1000; /// Entities with position component only. pub const N_POS: usize = 9000; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Position { pub x: f32, pub y: f32, } #[derive(Copy, Clone, Debug, PartialEq)] pub struct Velocity { pub dx: f32, pub dy: f32, } components!(Position, Velocity); pub struct PhysicsSystem { filter: ComponentFilter } impl PhysicsSystem { pub fn new() -> PhysicsSystem { PhysicsSystem { filter: ComponentFilter::new() .with::() .with::(), } } } impl System for PhysicsSystem { fn update(&mut self, world: &mut World, _queue: &EventQueue, _emitter: &mut EventEmitter, _dt: f32) { for entity in world.filter(&self.filter) { let &Velocity { dx, dy } = world.get(entity).unwrap(); let mut pos = world.get_mut::(entity).unwrap(); pos.x += dx; pos.y += dy; } } } pub struct RenderSystem { filter: ComponentFilter } impl RenderSystem { pub fn new() -> RenderSystem { RenderSystem { filter: ComponentFilter::new() .with::(), } } } impl System for RenderSystem { fn update(&mut self, world: &mut World, _queue: &EventQueue, _emitter: &mut EventEmitter, _dt: f32) { for entity in world.filter(&self.filter) { world.get::(entity); } } } fn build() -> Simulation { let mut world = World::new(); world.register::(); world.register::(); for _ in 0..N_POS_VEL { let entity = world.create(); world.add(entity, Position { x: 0.0, y: 0.0 }); world.add(entity, Velocity { dx: 0.0, dy: 0.0 }); } for _ in 0..N_POS { let entity = world.create(); world.add(entity, Position { x: 0.0, y: 0.0 }); } let mut queue = EventQueue::new(); let mut emitter = EventEmitter::new(); let mut simulation = Simulation::new(world, queue, emitter); simulation.register(PhysicsSystem::new()); simulation.register(RenderSystem::new()); simulation } #[bench] fn bench_build(b: &mut Bencher) { b.iter(|| build()); } #[bench] fn bench_update(b: &mut Bencher) { let mut simulation = build(); b.iter(|| { simulation.update(1.0); }); }