使用索引在WGPU中绘制类Minecraft纹理立方体的异常排查
WGPU绘制带纹理立方体:背面与顶面纹理坐标错乱问题
我用WGPU绘制类似Minecraft的带纹理立方体,已创建顶点缓冲与索引缓冲,纹理采样器的address_mode设置为Repeat,通过大于或小于0的纹理坐标重复dirt纹理。前、右、左三个面渲染正常,但背面纹理重复且翻转,顶面纹理完全混乱,目前尚未添加底面,先尝试解决该问题。
相关顶点与索引代码:
#[repr(C)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { pub position: [f32; 3], pub tex_coords: [f32; 2] } /// We arrange the vertices in counter-clockwise order: top, bottom left, bottom right. pub const VERTICES: &[Vertex] = &[ // FRONT Vertex {position: [-1.0, -1.0, 0.0], tex_coords: [0.0, 1.0]}, // 0 Vertex {position: [1.0, -1.0, 0.0], tex_coords: [1.0, 1.0]}, // 1 Vertex {position: [1.0, 1.0, 0.0], tex_coords: [1.0, 0.0]}, // 2 Vertex {position: [-1.0, 1.0, 0.0], tex_coords: [0.0, 0.0]}, // 3 // RIGHT Vertex {position: [1.0, -1.0, -2.0], tex_coords: [2.0, 1.0]}, // 4 Vertex {position: [1.0, 1.0, -2.0], tex_coords: [2.0, 0.0]}, // 5 // LEFT Vertex {position: [-1.0, -1.0, -2.0], tex_coords: [-1.0, 1.0]}, // 6 Vertex {position: [-1.0, 1.0, -2.0], tex_coords: [-1.0, 0.0]}, // 7 ]; pub const INDICES: &[u16] = &[ // FRONT 0, 1, 2, 2, 3, 0, // RIGHT 1, 4, 5, 5, 2, 1, // LEFT 6, 0, 3, 3, 7, 6, // BACK 6, 4, 5, 5, 7, 6, // TOP 3, 2, 5, 5, 7, 3 ];
纹理采样器配置:
let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::Repeat, address_mode_v: wgpu::AddressMode::Repeat, address_mode_w: wgpu::AddressMode::Repeat, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, ..Default::default() });
问题修复方案
1. 背面纹理错乱修复
背面纹理翻转是因为UV方向与视角不匹配,调整背面顶点的纹理坐标,让UV逻辑与正面统一:
// 修改VERTICES中索引6、7的纹理坐标: // LEFT/BACK Vertex {position: [-1.0, -1.0, -2.0], tex_coords: [1.0, 1.0]}, // 6 Vertex {position: [-1.0, 1.0, -2.0], tex_coords: [1.0, 0.0]}, // 7
从立方体背面观察时,U轴需要反转,这样重复的纹理方向才会和正面一致,不会出现翻转。
2. 顶面纹理混乱修复
顶面复用的顶点纹理坐标对应各自侧面,未形成连续UV映射。调整顶面相关顶点的纹理坐标,构建完整的UV区域:
// 修改VERTICES中顶面相关顶点的纹理坐标: // FRONT TOP Vertex {position: [-1.0, 1.0, 0.0], tex_coords: [0.0, 0.0]}, // 3 Vertex {position: [1.0, 1.0, 0.0], tex_coords: [1.0, 0.0]}, // 2 // RIGHT TOP Vertex {position: [1.0, 1.0, -2.0], tex_coords: [1.0, 1.0]}, // 5 // LEFT TOP Vertex {position: [-1.0, 1.0, -2.0], tex_coords: [0.0, 1.0]}, // 7
调整后顶面UV坐标形成从(0,0)到(1,0)再到(1,1)、(0,1)的连续映射,解决纹理混乱问题。
额外注意事项
- 所有面的顶点必须保持逆时针顺序,否则不仅会导致纹理异常,还可能触发背面剔除(若开启该功能)。
- 重复纹理的UV范围要保持连续区间(如0→1、1→2、-1→0),避免混合不同方向的UV值导致采样错乱。
内容的提问来源于stack exchange,提问作者NaniNoni
相关产品推荐
相关产品推荐

