[TUTORIAL5] Add textures
This commit is contained in:
parent
460dbc5a77
commit
9a4d651c44
10 changed files with 240 additions and 631 deletions
BIN
engine_core/src/happy-tree.png
Normal file
BIN
engine_core/src/happy-tree.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 28 KiB |
|
@ -1,5 +1,6 @@
|
|||
mod state;
|
||||
pub(self) mod vertex;
|
||||
pub(self) mod texture;
|
||||
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
struct VertexInput {
|
||||
[[location(0)]] position: vec3<f32>;
|
||||
[[location(1)]] color: vec3<f32>;
|
||||
[[location(1)]] tex_coords: vec2<f32>;
|
||||
};
|
||||
|
||||
struct VertexOutput {
|
||||
[[builtin(position)]] clip_position: vec4<f32>;
|
||||
[[location(0)]] color: vec3<f32>;
|
||||
[[location(0)]] tex_coords: vec2<f32>;
|
||||
};
|
||||
|
||||
[[stage(vertex)]]
|
||||
|
@ -13,12 +13,17 @@ fn vs_main(
|
|||
model: VertexInput,
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
out.color = model.color;
|
||||
out.tex_coords = model.tex_coords;
|
||||
out.clip_position = vec4<f32>(model.position, 1.0);
|
||||
return out;
|
||||
}
|
||||
|
||||
[[group(0), binding(0)]]
|
||||
var t_diffuse: texture_2d<f32>;
|
||||
[[group(0), binding(1)]]
|
||||
var s_diffuse: sampler;
|
||||
|
||||
[[stage(fragment)]]
|
||||
fn fs_main(in: VertexOutput) -> [[location(0)]] vec4<f32> {
|
||||
return vec4<f32>(in.color, 1.0);
|
||||
return textureSample(t_diffuse, s_diffuse, in.tex_coords);
|
||||
}
|
|
@ -1,20 +1,31 @@
|
|||
use wgpu::util::DeviceExt;
|
||||
use winit::{window::Window, event::WindowEvent};
|
||||
use super::vertex::Vertex;
|
||||
use wgpu::util::DeviceExt;
|
||||
use winit::{event::WindowEvent, window::Window};
|
||||
|
||||
const VERTICES: &[Vertex] = &[
|
||||
Vertex { position: [-0.0868241, 0.49240386, 0.0], color: [1.0, 0.0, 0.0] }, // A
|
||||
Vertex { position: [-0.49513406, 0.06958647, 0.0], color: [0.0, 1.0, 0.0] }, // B
|
||||
Vertex { position: [-0.21918549, -0.44939706, 0.0], color: [0.0, 1.0, 0.0] }, // C
|
||||
Vertex { position: [0.35966998, -0.3473291, 0.0], color: [1.0, 0.0, 0.0] }, // D
|
||||
Vertex { position: [0.44147372, 0.2347359, 0.0], color: [0.0, 0.0, 1.0] }, // E
|
||||
Vertex {
|
||||
position: [-0.0868241, 0.49240386, 0.0],
|
||||
tex_coords: [0.4131759, 0.00759614],
|
||||
}, // A
|
||||
Vertex {
|
||||
position: [-0.49513406, 0.06958647, 0.0],
|
||||
tex_coords: [0.0048659444, 0.43041354],
|
||||
}, // B
|
||||
Vertex {
|
||||
position: [-0.21918549, -0.44939706, 0.0],
|
||||
tex_coords: [0.28081453, 0.949397],
|
||||
}, // C
|
||||
Vertex {
|
||||
position: [0.35966998, -0.3473291, 0.0],
|
||||
tex_coords: [0.85967, 0.84732914],
|
||||
}, // D
|
||||
Vertex {
|
||||
position: [0.44147372, 0.2347359, 0.0],
|
||||
tex_coords: [0.9414737, 0.2652641],
|
||||
}, // E
|
||||
];
|
||||
|
||||
const INDICES: &[u16] = &[
|
||||
0, 1, 4,
|
||||
1, 2, 4,
|
||||
2, 3, 4,
|
||||
];
|
||||
const INDICES: &[u16] = &[0, 1, 4, 1, 2, 4, 2, 3, 4];
|
||||
|
||||
pub struct State {
|
||||
pub surface: wgpu::Surface,
|
||||
|
@ -25,8 +36,11 @@ pub struct State {
|
|||
render_pipeline: wgpu::RenderPipeline,
|
||||
vertex_buffer: wgpu::Buffer,
|
||||
// num_vertices: u32,
|
||||
index_buffer: wgpu::Buffer,
|
||||
index_buffer: wgpu::Buffer,
|
||||
num_indices: u32,
|
||||
diffuse_bind_group: wgpu::BindGroup,
|
||||
#[allow(dead_code)]
|
||||
diffuse_texture: super::texture::Texture,
|
||||
}
|
||||
|
||||
impl State {
|
||||
|
@ -38,13 +52,14 @@ impl State {
|
|||
// Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
|
||||
let instance = wgpu::Instance::new(wgpu::Backends::all());
|
||||
let surface = unsafe { instance.create_surface(window) };
|
||||
let adapter = instance.request_adapter(
|
||||
&wgpu::RequestAdapterOptions {
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::default(),
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
},
|
||||
).await.unwrap();
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// let adapter = instance
|
||||
// .enumerate_adapters(wgpu::Backends::all())
|
||||
|
@ -55,21 +70,23 @@ impl State {
|
|||
// .next()
|
||||
// .unwrap();
|
||||
|
||||
|
||||
let (device, queue) = adapter.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
features: wgpu::Features::empty(),
|
||||
// WebGL doesn't support all of wgpu's features, so if
|
||||
// we're building for the web we'll have to disable some.
|
||||
limits: if cfg!(target_arch = "wasm32") {
|
||||
wgpu::Limits::downlevel_webgl2_defaults()
|
||||
} else {
|
||||
wgpu::Limits::default()
|
||||
let (device, queue) = adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
features: wgpu::Features::empty(),
|
||||
// WebGL doesn't support all of wgpu's features, so if
|
||||
// we're building for the web we'll have to disable some.
|
||||
limits: if cfg!(target_arch = "wasm32") {
|
||||
wgpu::Limits::downlevel_webgl2_defaults()
|
||||
} else {
|
||||
wgpu::Limits::default()
|
||||
},
|
||||
label: None,
|
||||
},
|
||||
label: None,
|
||||
},
|
||||
None, // Trace path
|
||||
).await.unwrap();
|
||||
None, // Trace path
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
|
@ -79,24 +96,63 @@ impl State {
|
|||
present_mode: wgpu::PresentMode::Fifo,
|
||||
};
|
||||
surface.configure(&device, &config);
|
||||
|
||||
let vertex_buffer = device.create_buffer_init(
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Vertex Buffer"),
|
||||
contents: bytemuck::cast_slice(VERTICES),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
}
|
||||
);
|
||||
|
||||
let diffuse_bytes = include_bytes!("happy-tree.png");
|
||||
let diffuse_texture =
|
||||
super::texture::Texture::from_bytes(&device, &queue, diffuse_bytes, "happy-tree.png")
|
||||
.unwrap();
|
||||
|
||||
let texture_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
label: Some("texture_bind_group_layout"),
|
||||
});
|
||||
|
||||
let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &texture_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&diffuse_texture.view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&diffuse_texture.sampler),
|
||||
},
|
||||
],
|
||||
label: Some("diffuse_bind_group"),
|
||||
});
|
||||
|
||||
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Vertex Buffer"),
|
||||
contents: bytemuck::cast_slice(VERTICES),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
|
||||
// let num_vertices = VERTICES.len() as u32;
|
||||
|
||||
let index_buffer = device.create_buffer_init(
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Index Buffer"),
|
||||
contents: bytemuck::cast_slice(INDICES),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
}
|
||||
);
|
||||
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Index Buffer"),
|
||||
contents: bytemuck::cast_slice(INDICES),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
});
|
||||
let num_indices = INDICES.len() as u32;
|
||||
|
||||
let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
|
||||
|
@ -105,21 +161,19 @@ impl State {
|
|||
});
|
||||
|
||||
let render_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[&texture_bind_group_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Render Pipeline"),
|
||||
layout: Some(&render_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
buffers: &[
|
||||
Vertex::desc(),
|
||||
],
|
||||
buffers: &[Vertex::desc()],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
|
@ -162,6 +216,8 @@ impl State {
|
|||
// num_vertices,
|
||||
index_buffer,
|
||||
num_indices,
|
||||
diffuse_bind_group,
|
||||
diffuse_texture,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -179,17 +235,19 @@ impl State {
|
|||
false
|
||||
}
|
||||
|
||||
pub fn update(&mut self) {
|
||||
|
||||
}
|
||||
pub fn update(&mut self) {}
|
||||
|
||||
pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
|
||||
let output = self.surface.get_current_texture()?;
|
||||
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Render Encoder"),
|
||||
});
|
||||
|
||||
let view = output
|
||||
.texture
|
||||
.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Render Encoder"),
|
||||
});
|
||||
|
||||
{
|
||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Render Pass"),
|
||||
|
@ -199,16 +257,14 @@ impl State {
|
|||
view: &view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(
|
||||
wgpu::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
}
|
||||
),
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
}),
|
||||
store: true,
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
depth_stencil_attachment: None,
|
||||
|
@ -216,16 +272,17 @@ impl State {
|
|||
|
||||
render_pass.set_pipeline(&self.render_pipeline);
|
||||
|
||||
render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]);
|
||||
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
||||
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
|
||||
// render_pass.draw(0..self.num_vertices, 0..1);
|
||||
render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
|
||||
}
|
||||
|
||||
|
||||
// submit will accept anything that implements IntoIter
|
||||
self.queue.submit(std::iter::once(encoder.finish()));
|
||||
output.present();
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
78
engine_core/src/texture.rs
Normal file
78
engine_core/src/texture.rs
Normal file
|
@ -0,0 +1,78 @@
|
|||
use anyhow::*;
|
||||
use image::GenericImageView;
|
||||
|
||||
pub struct Texture {
|
||||
pub texture: wgpu::Texture,
|
||||
pub view: wgpu::TextureView,
|
||||
pub sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
pub fn from_bytes(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
bytes: &[u8],
|
||||
label: &str,
|
||||
) -> Result<Self> {
|
||||
let img = image::load_from_memory(bytes)?;
|
||||
Self::from_image(device, queue, &img, Some(label))
|
||||
}
|
||||
|
||||
pub fn from_image(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
img: &image::DynamicImage,
|
||||
label: Option<&str>,
|
||||
) -> Result<Self> {
|
||||
let rgba = img.to_rgba8();
|
||||
let dimensions = img.dimensions();
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width: dimensions.0,
|
||||
height: dimensions.1,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label,
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
});
|
||||
|
||||
queue.write_texture(
|
||||
wgpu::ImageCopyTexture {
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
texture: &texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
},
|
||||
&rgba,
|
||||
wgpu::ImageDataLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: std::num::NonZeroU32::new(4 * dimensions.0),
|
||||
rows_per_image: std::num::NonZeroU32::new(dimensions.1),
|
||||
},
|
||||
size,
|
||||
);
|
||||
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu::FilterMode::Nearest,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
texture,
|
||||
view,
|
||||
sampler,
|
||||
})
|
||||
}
|
||||
}
|
|
@ -2,13 +2,13 @@
|
|||
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Vertex {
|
||||
pub position: [f32; 3],
|
||||
pub color: [f32; 3],
|
||||
pub tex_coords: [f32; 2],
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
|
||||
const ATTRIBS: [wgpu::VertexAttribute; 2] =
|
||||
wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3];
|
||||
wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2];
|
||||
|
||||
pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
|
||||
use std::mem;
|
||||
|
@ -33,7 +33,7 @@ impl Vertex {
|
|||
// wgpu::VertexAttribute {
|
||||
// offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
|
||||
// shader_location: 1,
|
||||
// format: wgpu::VertexFormat::Float32x3,
|
||||
// format: wgpu::VertexFormat::Float32x2,
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue