🦆 渲染管线、Depth、Camera、Light、Transform、bevy_ecs|Wgpu PBR 开发日志 #0000
2025-01-02

现阶段展示出的代码为早期开发版本,未来大概率都会被重构
Mesh
模型的数据结构
-
Model
Material
-
Transform -
Camera -
Light -
[Material‘s]
-
Transform 的 BindGroup 由 MeshRenderer 提供。
Texture
pub struct UploadedImage {
pub size: wgpu::Extent3d,
pub texture: Texture,
pub view: TextureView,
pub sampler: Sampler,
}
实现 Camera
impl Camera{
...
pub fn build_view_projection_matrix(&self) -> Matrix4<f32> {
let view = Matrix4::look_at_rh(self.eye, self.target, self.up);
let proj = perspective(cgmath::Deg(self.fovy), self.aspect, self.znear, self.zfar);
return OPENGL_TO_WGPU_MATRIX * proj * view;
}
}
#[rustfmt::skip]
pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::new(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0,
);
RenderCamera
#[derive(Resource)]
pub struct RenderCamera {
pub camera: Camera,
pub buffer: Arc<wgpu::Buffer>,
pub bind_group_layout: Arc<BindGroupLayout>,
pub bind_group: Arc<BindGroup>,
}
impl RenderCamera {
pub fn new(device: &wgpu::Device, aspect: f32) -> RenderCamera {
let camera = Camera::new(aspect);
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
...
});
let camera_bind_group_layout =
Arc::new(device.create_bind_group_layout(&CameraUniform::layout_desc()));
let camera_bind_group = Arc::new(device.create_bind_group(&wgpu::BindGroupDescriptor {
...
}));
RenderCamera {
camera,
buffer: Arc::new(camera_buffer),
bind_group_layout: camera_bind_group_layout,
bind_group: camera_bind_group,
}
}
}
实现 Transform
仅为实现方便才这样实现,不值得参考,寻找参考请见 Bevy 的 Transform 逻辑实现
#[derive(Component)]
pub struct Transform {
pub parent: Option<Entity>,
pub children: Vec<Entity>,
pub position: Point3<f32>,
pub rotation: Quaternion<f32>,
pub scale: Vector3<f32>,
}
数据大小对齐
数据类型 <f32> | f32 | vec2 | vec3 | vec4 | mat3x3 | mat4x4 |
大小 / 字节 | 4 | 8 | 16 | 16 | 48 (3 * vec3) | 64 (4 * vec3) |
pub struct TransformUniform {
pub model: [[f32; 4]; 4],
pub rotation: [[f32; 3]; 3],
pub padding: [f32; 3],
}
封装
#[derive(Component, Default)]
pub struct MeshRenderer {
pub mesh: Option<Arc<UploadedMesh>>,
pub transform_bind_group: Option<Arc<BindGroup>>,
pub transform_buffer: Option<Arc<Buffer>>,
}
实现平行光
#[repr(C, align(16))]
#[derive(Debug, Clone, Copy)]
pub struct LightUniform {
pub direction: [f32; 3],
pub padding1: f32,
pub color: [f32; 4],
pub intensity: f32,
pub padding2: [f32; 3],
}
Engine Lifetime
input()
handle_redraw()
pre_update() // 更新 Time
update() //游戏逻辑
post_update() // 更新 Unifoms to GPU
render() // 渲染
其它
-
相机的深度贴图被写在 depth_texture 中,未来会用到。 -
一个简单的 Input 用于记录输入 -
一个简单的 Time 用于记录 delta time
相关链接