Seija
首页
Travellings
登录
注册
首页
文章
Rust的ECS库specs
### 简单说一下ECS 我们知道ECS是Entity-component system的简写.ECS由三部分组成, `Entity`(实体),`Component`(组件),和`System`.这里其实名字起的非常不够抽象和合理.我们可以把Component认为是Data,把System认为是处理data的副作用函数. 而Entity只是对Component进行分组而已. 所以这其实在抽象上只是对函数式的一种模仿. 当然如果ECS只是一个用于抽象的概念那么我们研究他也就没什么意义了.他其实主要是有性能方面的优势. 一个是**缓存命中友好**,一个是利于并行(改成函数式当然利于并行). 缓存命中友好主要是他从一个Update不同对象的树变成了一个Structure of Arrays的内存友好的的Component数组. ### 开始例子 #### Component ``` use specs::{Component, VecStorage}; #[derive(Debug)] struct Position { x: f32, y: f32, } impl Component for Position { type Storage = VecStorage
; } #[derive(Debug)] struct Velocity { x: f32, y: f32, } impl Component for Velocity { type Storage = VecStorage
; } ``` 这里定义了两个组件.打开他的`specs-derive`特性.可以更简洁的定义组件. ``` [dependencies] specs = { version = "0.15.0", features = ["specs-derive"] } ``` ``` use specs::{Component, VecStorage}; #[derive(Component, Debug)] #[storage(VecStorage)] struct Position { x: f32, y: f32, } #[derive(Component, Debug)] #[storage(VecStorage)] struct Velocity { x: f32, y: f32, } ``` 如果不指定`#[storage(VecStorage)]`那么默认会使用`DenseVecStorage`. #### World ``` use specs::{World, WorldExt, Builder}; let mut world = World::new(); world.register::
(); world.register::
(); ``` 这会创建`Position`和`Velocity`的存储. ``` let ball = world.create_entity().with(Position { x: 4.0, y: 7.0 }).build(); ``` 这样就创建了一个拥有Position组件的实体. #### System ``` use specs::{ReadStorage, System}; struct HelloWorld; impl<'a> System<'a> for HelloWorld { type SystemData = ReadStorage<'a, Position>; fn run(&mut self, position: Self::SystemData) { use specs::Join; for position in position.join() { println!("Hello, {:?}", &position); } } } ``` 通过 SystemData 可以关联需要的组件.
登录
登录
注册
最热文章
引擎中Template DSL的设计思考总结
10-19
ReaderT 设计模式
04-23
非主流引擎开发不出来 (n+1) : purescript侧结构设计
04-04
FRP系统的设计
03-17
非主流引擎开发不出来 (1) : 轻骨架
02-11
非主流引擎开发不出来 (0) : 引擎定位
12-09
Rust的ECS库specs
11-20
Haskell类型类高级扩展详细说明
05-31
CMake 速览
05-29
尼采导读:超人与永恒轮回
02-24
为什么elm的结构并不是最合理的?
02-20
React速览
02-20
尼采命运之爱
02-18
AspNetCore 速览
02-17
由Haskell和面向对象引出的关于抽象的思考
12-26
二进制文件压缩工具upx
12-24
Reflex介绍
12-17
Web的前端渲染和WebApi
12-16
前端FRP框架深度踩坑
12-16
Yesod - RESTful (11)
12-16
链接
github
gitee