diff --git a/.gitignore b/.gitignore index 8c3fe3ed..7326f103 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ node_modules/ target/ -.vscode/ \ No newline at end of file +.vscode/ + +image.png \ No newline at end of file diff --git a/code/Cargo.toml b/code/Cargo.toml index ba07eab2..bc589d3b 100644 --- a/code/Cargo.toml +++ b/code/Cargo.toml @@ -22,6 +22,10 @@ path = "src/beginner/tutorial3-pipeline/main.rs" name = "tutorial4-buffer" path = "src/beginner/tutorial4-buffer/main.rs" +[[bin]] +name = "tutorial5-textures" +path = "src/beginner/tutorial5-textures/main.rs" + [[bin]] name = "windowless" path = "src/intermediate/windowless/main.rs" diff --git a/code/src/beginner/tutorial5-textures/happy-tree.png b/code/src/beginner/tutorial5-textures/happy-tree.png new file mode 100644 index 00000000..ead2f03b Binary files /dev/null and b/code/src/beginner/tutorial5-textures/happy-tree.png differ diff --git a/code/src/beginner/tutorial5-textures/main.rs b/code/src/beginner/tutorial5-textures/main.rs new file mode 100644 index 00000000..c0681006 --- /dev/null +++ b/code/src/beginner/tutorial5-textures/main.rs @@ -0,0 +1,380 @@ +use winit::{ + event::*, + event_loop::{EventLoop, ControlFlow}, + window::{Window, WindowBuilder}, +}; + +#[repr(C)] +#[derive(Copy, Clone, Debug)] +struct Vertex { + position: [f32; 3], + tex_coords: [f32; 2], +} + +impl Vertex { + fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a> { + use std::mem; + wgpu::VertexBufferDescriptor { + stride: mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::InputStepMode::Vertex, + attributes: &[ + wgpu::VertexAttributeDescriptor { + offset: 0, + shader_location: 0, + format: wgpu::VertexFormat::Float3, + }, + wgpu::VertexAttributeDescriptor { + offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, + shader_location: 1, + format: wgpu::VertexFormat::Float2, + }, + ] + } + } +} + +const VERTICES: &[Vertex] = &[ + Vertex { position: [-0.0868241, -0.49240386, 0.0], tex_coords: [0.4131759, 1.0 - 0.99240386], }, // A + Vertex { position: [-0.49513406, -0.06958647, 0.0], tex_coords: [0.0048659444, 1.0 - 0.56958646], }, // B + Vertex { position: [-0.21918549, 0.44939706, 0.0], tex_coords: [0.28081453, 1.0 - 0.050602943], }, // C + Vertex { position: [0.35966998, 0.3473291, 0.0], tex_coords: [0.85967, 1.0 - 0.15267089], }, // D + Vertex { position: [0.44147372, -0.2347359, 0.0], tex_coords: [0.9414737, 1.0 - 0.7347359], }, // E +]; + +const INDICES: &[u16] = &[ + 0, 1, 4, + 1, 2, 4, + 2, 3, 4, +]; + +struct State { + surface: wgpu::Surface, + device: wgpu::Device, + sc_desc: wgpu::SwapChainDescriptor, + swap_chain: wgpu::SwapChain, + + render_pipeline: wgpu::RenderPipeline, + + vertex_buffer: wgpu::Buffer, + index_buffer: wgpu::Buffer, + num_indices: u32, + + diffuse_texture: wgpu::Texture, + diffuse_texture_view: wgpu::TextureView, + diffuse_sampler: wgpu::Sampler, + diffuse_bind_group: wgpu::BindGroup, + + hidpi_factor: f64, + size: winit::dpi::LogicalSize, +} + +impl State { + fn new(window: &Window) -> Self { + let hidpi_factor = window.hidpi_factor(); + let size = window.inner_size(); + let physical_size = size.to_physical(hidpi_factor); + + let instance = wgpu::Instance::new(); + + use raw_window_handle::HasRawWindowHandle as _; + let surface = instance.create_surface(window.raw_window_handle()); + + let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: Default::default(), + }); + + let mut device = adapter.request_device(&wgpu::DeviceDescriptor { + extensions: wgpu::Extensions { + anisotropic_filtering: false, + }, + limits: Default::default(), + }); + + let sc_desc = wgpu::SwapChainDescriptor { + usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: physical_size.width.round() as u32, + height: physical_size.height.round() as u32, + present_mode: wgpu::PresentMode::Vsync, + }; + let swap_chain = device.create_swap_chain(&surface, &sc_desc); + + let diffuse_bytes = include_bytes!("happy-tree.png"); + let diffuse_image = image::load_from_memory(diffuse_bytes).unwrap(); + let diffuse_rgba = diffuse_image.as_rgba8().unwrap(); + + use image::GenericImageView; + let dimensions = diffuse_image.dimensions(); + + let size3d = wgpu::Extent3d { + width: dimensions.0, + height: dimensions.1, + depth: 1, + }; + let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor { + size: size3d, + array_layer_count: 1, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8UnormSrgb, + usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, + }); + + let diffuse_buffer = device + .create_buffer_mapped(diffuse_rgba.len(), wgpu::BufferUsage::COPY_SRC) + .fill_from_slice(&diffuse_rgba); + + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + todo: 0, + }); + + encoder.copy_buffer_to_texture( + wgpu::BufferCopyView { + buffer: &diffuse_buffer, + offset: 0, + row_pitch: 4 * dimensions.0, + image_height: dimensions.1, + }, + wgpu::TextureCopyView { + texture: &diffuse_texture, + mip_level: 0, + array_layer: 0, + origin: wgpu::Origin3d::ZERO, + }, + size3d, + ); + + device.get_queue().submit(&[encoder.finish()]); + + let diffuse_texture_view = diffuse_texture.create_default_view(); + let diffuse_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, + lod_min_clamp: -100.0, + lod_max_clamp: 100.0, + compare_function: wgpu::CompareFunction::Always, + }); + + let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + bindings: &[ + wgpu::BindGroupLayoutBinding { + binding: 0, + visibility: wgpu::ShaderStage::FRAGMENT, + ty: wgpu::BindingType::SampledTexture { + multisampled: false, + dimension: wgpu::TextureViewDimension::D2, + }, + }, + wgpu::BindGroupLayoutBinding { + binding: 1, + visibility: wgpu::ShaderStage::FRAGMENT, + ty: wgpu::BindingType::Sampler, + }, + ], + }); + + let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: &texture_bind_group_layout, + bindings: &[ + wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::TextureView(&diffuse_texture_view), + }, + wgpu::Binding { + binding: 1, + resource: wgpu::BindingResource::Sampler(&diffuse_sampler), + } + ], + }); + + let vs_src = include_str!("shader.vert"); + let fs_src = include_str!("shader.frag"); + let vs_spirv = glsl_to_spirv::compile(vs_src, glsl_to_spirv::ShaderType::Vertex).unwrap(); + let fs_spirv = glsl_to_spirv::compile(fs_src, glsl_to_spirv::ShaderType::Fragment).unwrap(); + let vs_data = wgpu::read_spirv(vs_spirv).unwrap(); + let fs_data = wgpu::read_spirv(fs_spirv).unwrap(); + let vs_module = device.create_shader_module(&vs_data); + let fs_module = device.create_shader_module(&fs_data); + + let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + bind_group_layouts: &[&texture_bind_group_layout], + }); + + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + layout: &render_pipeline_layout, + vertex_stage: wgpu::ProgrammableStageDescriptor { + module: &vs_module, + entry_point: "main", + }, + fragment_stage: Some(wgpu::ProgrammableStageDescriptor { + module: &fs_module, + entry_point: "main", + }), + rasterization_state: Some(wgpu::RasterizationStateDescriptor { + front_face: wgpu::FrontFace::Ccw, + cull_mode: wgpu::CullMode::Back, + depth_bias: 0, + depth_bias_slope_scale: 0.0, + depth_bias_clamp: 0.0, + }), + primitive_topology: wgpu::PrimitiveTopology::TriangleList, + color_states: &[ + wgpu::ColorStateDescriptor { + format: sc_desc.format, + color_blend: wgpu::BlendDescriptor::REPLACE, + alpha_blend: wgpu::BlendDescriptor::REPLACE, + write_mask: wgpu::ColorWrite::ALL, + }, + ], + depth_stencil_state: None, + index_format: wgpu::IndexFormat::Uint16, + vertex_buffers: &[ + Vertex::desc(), + ], + sample_count: 1, + sample_mask: !0, + alpha_to_coverage_enabled: false, + }); + + let vertex_buffer = device + .create_buffer_mapped(VERTICES.len(), wgpu::BufferUsage::VERTEX) + .fill_from_slice(VERTICES); + let index_buffer = device + .create_buffer_mapped(INDICES.len(), wgpu::BufferUsage::INDEX) + .fill_from_slice(INDICES); + let num_indices = INDICES.len() as u32; + + Self { + surface, + device, + sc_desc, + swap_chain, + render_pipeline, + vertex_buffer, + index_buffer, + num_indices, + diffuse_texture, + diffuse_texture_view, + diffuse_sampler, + diffuse_bind_group, + hidpi_factor, + size, + } + } + + fn update_hidpi_and_resize(&mut self, new_hidpi_factor: f64) { + self.hidpi_factor = new_hidpi_factor; + self.resize(self.size); + } + + fn resize(&mut self, new_size: winit::dpi::LogicalSize) { + let physical_size = new_size.to_physical(self.hidpi_factor); + self.size = new_size; + self.sc_desc.width = physical_size.width.round() as u32; + self.sc_desc.height = physical_size.height.round() as u32; + self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); + } + + fn input(&mut self, event: &WindowEvent) -> bool { + false + } + + fn update(&mut self) { + + } + + fn render(&mut self) { + let frame = self.swap_chain.get_next_texture(); + + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + todo: 0, + }); + + { + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[ + wgpu::RenderPassColorAttachmentDescriptor { + attachment: &frame.view, + resolve_target: None, + load_op: wgpu::LoadOp::Clear, + store_op: wgpu::StoreOp::Store, + clear_color: wgpu::Color { + r: 0.1, + g: 0.2, + b: 0.3, + a: 1.0, + }, + } + ], + depth_stencil_attachment: None, + }); + + render_pass.set_pipeline(&self.render_pipeline); + render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); + render_pass.set_vertex_buffers(0, &[(&self.vertex_buffer, 0)]); + render_pass.set_index_buffer(&self.index_buffer, 0); + render_pass.draw_indexed(0..self.num_indices, 0, 0..1); + } + + self.device.get_queue().submit(&[ + encoder.finish() + ]); + } +} + +fn main() { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new() + .build(&event_loop) + .unwrap(); + + let mut state = State::new(&window); + + event_loop.run(move |event, _, control_flow| { + match event { + Event::WindowEvent { + ref event, + window_id, + } if window_id == window.id() => if state.input(event) { + *control_flow = ControlFlow::Wait; + } else { + match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::KeyboardInput { + input, + .. + } => { + match input { + KeyboardInput { + state: ElementState::Pressed, + virtual_keycode: Some(VirtualKeyCode::Escape), + .. + } => *control_flow = ControlFlow::Exit, + _ => *control_flow = ControlFlow::Wait, + } + } + WindowEvent::Resized(logical_size) => { + state.resize(*logical_size); + *control_flow = ControlFlow::Wait; + } + WindowEvent::HiDpiFactorChanged(new_hidpi_factor) => { + state.update_hidpi_and_resize(*new_hidpi_factor); + *control_flow = ControlFlow::Wait; + } + _ => *control_flow = ControlFlow::Wait, + } + } + Event::EventsCleared => { + state.update(); + state.render(); + *control_flow = ControlFlow::Wait; + } + _ => *control_flow = ControlFlow::Wait, + } + }); +} \ No newline at end of file diff --git a/code/src/beginner/tutorial5-textures/shader.frag b/code/src/beginner/tutorial5-textures/shader.frag new file mode 100644 index 00000000..9b033114 --- /dev/null +++ b/code/src/beginner/tutorial5-textures/shader.frag @@ -0,0 +1,11 @@ +#version 450 + +layout(location=0) in vec2 v_tex_coords; +layout(location=0) out vec4 f_color; + +layout(set = 0, binding = 0) uniform texture2D t_diffuse; +layout(set = 0, binding = 1) uniform sampler s_diffuse; + +void main() { + f_color = texture(sampler2D(t_diffuse, s_diffuse), v_tex_coords); +} \ No newline at end of file diff --git a/code/src/beginner/tutorial5-textures/shader.vert b/code/src/beginner/tutorial5-textures/shader.vert new file mode 100644 index 00000000..54ce45c7 --- /dev/null +++ b/code/src/beginner/tutorial5-textures/shader.vert @@ -0,0 +1,11 @@ +#version 450 + +layout(location=0) in vec3 a_position; +layout(location=1) in vec2 a_tex_coords; + +layout(location=0) out vec2 v_tex_coords; + +void main() { + v_tex_coords = a_tex_coords; + gl_Position = vec4(a_position, 1.0); +} \ No newline at end of file diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 63eb661f..16bd12e2 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -17,6 +17,7 @@ module.exports = { '/beginner/tutorial2-swapchain', '/beginner/tutorial3-pipeline/', '/beginner/tutorial4-buffer/', + '/beginner/tutorial5-textures/', ], }, { diff --git a/docs/beginner/tutorial5-textures/README.md b/docs/beginner/tutorial5-textures/README.md new file mode 100644 index 00000000..c8f9c0a8 --- /dev/null +++ b/docs/beginner/tutorial5-textures/README.md @@ -0,0 +1,364 @@ +# Textures and bind groups + +Up to this point we have been drawing super simple shapes. While we can make a game with just triangles, but trying to draw highly detailed objects would massively limit what devices could even run our game. We can get around this problem with textures. Textures are images overlayed over a triangle mesh to make the mesh seem more detailed. There are multiple types of textures such as normal maps, bump maps, specular maps, and diffuse maps. We're going to talk about diffuse maps, or in laymens terms, the color texture. + +## Loading an image from a file + +If we want to map an image to our mesh, we first need an image. Let's use this happy little tree. + +![a happy tree](./happy-tree.png) + +We'll use the [image crate](https://crates.io/crates/image) to load our tree. In `State`'s `new()` method add the following just after creating the `swap_chain`: + +```rust +let diffuse_bytes = include_bytes!("happy-tree.png"); +let diffuse_image = image::load_from_memory(diffuse_bytes).unwrap(); +let diffuse_rgba = diffuse_image.as_rgba8().unwrap(); + +use image::GenericImageView; +let dimensions = diffuse_image.dimensions(); +``` + +Here we just grab the bytes from our image file, and load them into an image, which we then convert into a `Vec` of rgba bytes. We also save the image's dimensions for when we create the actual `Texture`. Speaking of creating the actual `Texture`. + +```rust +let size = wgpu::Extent3d { + width: dimensions.0, + height: dimensions.1, + depth: 1, +}; +let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor { + // All textures are stored as 3d, we represent our 2d texture + // by setting depth to 1. + size: wgpu::Extent3d { + width: dimensions.0, + height: dimensions.1, + depth: 1, + }, + // You can store multiple textures of the same size in one + // Texture object + array_layer_count: 1, + mip_level_count: 1, // We'll talk about this a little later + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8UnormSrgb, + // SAMPLED tells wgpu that we want to use this texture in shaders + // COPY_DST means that we want to copy data to this texture + usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, +}); +``` + +## Getting data into a Texture + +The `Texture` struct has no methods to interact with the data directly. We actually need to load the data into a `Buffer` and copy it into the `Texture`. First we need to create a buffer big enough to hold our texture data. Luckily we have `diffuse_rgba`! + +```rust +let diffuse_buffer = device + .create_buffer_mapped(diffuse_rgba.len(), wgpu::BufferUsage::COPY_SRC) + .fill_from_slice(&diffuse_rgba); +``` + +We specified our `diffuse_buffer` to be `COPY_SRC` so that we can copy it to our `diffuse_texture`. We preform the copy using a `CommandEncoder`. We'll need to change `device`'s mutablility so we can submit the resulting `CommandBuffer`. + +```rust +let mut device = // ... + +// ... + +let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + todo: 0, +}); + +encoder.copy_buffer_to_texture( + wgpu::BufferCopyView { + buffer: &diffuse_buffer, + offset: 0, + row_pitch: 4 * dimensions.0, // the width of the texture in bytes + image_height: dimensions.1, + }, + wgpu::TextureCopyView { + texture: &diffuse_texture, + mip_level: 0, + array_layer: 0, + origin: wgpu::Origin3d::ZERO, + }, + size, +); + +device.get_queue().submit(&[encoder.finish()]); +``` + +## TextureViews and Samplers + +Now that our texture has data in it, we need a way to use it. This is where a `TextureView` and a `Sampler`. A `TextureView` offers us a *view* into our texture. A `Sampler` controls how the `Texture` is *sampled*. Sampling works similar to the eyedropper tool in Gimp/Photoshop. Our program supplies a coordinate on the texture (known as a texture coordinate), and the sampler then returns a color back based on it's internal parameters. + +Let's define our `diffuse_texture_view` and `diffuse_sampler` now. + +```rust +// We don't need to configure the texture view much, so let's +// let wgpu define it. +let diffuse_texture_view = diffuse_texture.create_default_view(); + +let diffuse_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, + lod_min_clamp: -100.0, + lod_max_clamp: 100.0, + compare_function: wgpu::CompareFunction::Always, +}); +``` + +The `address_mode_*` parameter's determine what to do if the sampler get's a texture coordinate that's outside of the texture. There's a few that we can use. +* `ClampToEdge`: Any texture coordinates outside the texture will return the color of the nearest pixel on the edges of the texture. +* `Repeat`: The texture will repeat as texture coordinates exceed the textures dimensions. +* `MirrorRepeat`: Similar to `Repeat`, but the image will flip when going over boundaries. + +The `mag_filter` and `min_filter` options describe what to do when a fragment covers multiple pixels, or there are multiple fragments for one pixel respectively. This often comes into play when viewing a surface from up close, or far away. There are 2 options: +* `Linear`: This option will attempt to blend the in-between fragments so that they seem to flow together. +* `Nearest`: In-between fragments will use the color of the nearest pixel. This creates an image that's crisper from far away, but pixelated when view from close up. This can be desirable however if your textures are designed to be pixelated such is in pixel art games, or voxel games like Minecraft. + +Mipmaps are a complex topic, and will require [their own section](/todo). Suffice to say `mipmap_filter` functions similar to `(mag/min)_filter` as it tells the sampler how to blend between mipmaps. + +`lod_(min/max)_clamp` are also related to mipmapping, so will skip over them. + +The `compare_function` is often use in filtering. This is used in techniques such as [shadow mapping](/todo). We don't really care here, but the options are `Never`, `Less`, `Equal`, `LessEqual`, `Greater`, `NotEqual`, `GreaterEqual`, and `Always`. + +All these different resources are nice and all, but they doesn't do us much good if we can't plug them in anywhere. This is where `BindGroup`s and `PipelineLayout`s come in. + +## The BindGroup + +A `BindGroup` describes a set of resources and how they can be accessed by a shader. We create a `BindGroup` using a `BindGroupLayout`. Let's make one of those first. + +```rust +let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + bindings: &[ + wgpu::BindGroupLayoutBinding { + binding: 0, + visibility: wgpu::ShaderStage::FRAGMENT, + ty: wgpu::BindingType::SampledTexture { + multisampled: false, + dimension: wgpu::TextureViewDimension::D2, + }, + }, + wgpu::BindGroupLayoutBinding { + binding: 1, + visibility: wgpu::ShaderStage::FRAGMENT, + ty: wgpu::BindingType::Sampler, + }, + ], +}); +``` + +Our `texture_bind_group_layout` has two bindings: one for a sampled texture at binding 0, and one for a sampler at binding 1. Both of these bindings are visible only to the fragment shader as specified by `FRAGMENT`. The possible values are any bit combination of `NONE`, `VERTEX`, `FRAGMENT`, or `COMPUTE`. Most of the time we'll only use `FRAGMENT` for textures and samplers, but it's good to know what's available. + +With `texture_bind_group_layout`, we can now create our `BindGroup`. + +```rust +let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: &texture_bind_group_layout, + bindings: &[ + wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::TextureView(&diffuse_texture_view), + }, + wgpu::Binding { + binding: 1, + resource: wgpu::BindingResource::Sampler(&diffuse_sampler), + } + ], +}); +``` + +Looking at this you might get a bit of déjà vu. That's because a `BindGroup` is a more specific declaration of the `BindGroupLayout`. The reason why these are separate is to allow us to swap out `BindGroup`s on the fly, so long as they all share the same `BindGroupLayout`. For each texture and sampler we create, we need to create a `BindGroup`. + +Now that we have our `diffuse_bind_group`, let's add our texture information to the `State` struct. + +```rust +struct State { + // ... + + diffuse_texture: wgpu::Texture, + diffuse_texture_view: wgpu::TextureView, + diffuse_sampler: wgpu::Sampler, + diffuse_bind_group: wgpu::BindGroup, + + // ... +} + +// ... +impl State { + fn new() -> Self { + // ... + Self { + surface, + device, + sc_desc, + swap_chain, + render_pipeline, + vertex_buffer, + index_buffer, + num_indices, + diffuse_texture, + diffuse_texture_view, + diffuse_sampler, + diffuse_bind_group, + hidpi_factor, + size, + } + } +} + +``` + +We actually use the bind group in the `render()` function. + +```rust +// render() +render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); +``` + +## PipelineLayout + +Remember the `PipelineLayout` we created back in [the pipeline section](/beginner/tutorial3-pipeline#how-do-we-use-the-shaders)? This is finally the time when we get to actually use it. The `PipelineLayout` contains a list of `BindGroupLayout`s that the pipeline can use. Modify `render_pipeline_layout` to use our `texture_bind_group_layout`. + +```rust +let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + bind_group_layouts: &[&texture_bind_group_layout], +}); +``` + +## A change to the VERTICES +There's a few things we need to change about our `Vertex` definition. Up to now we've been using a `color` attribute to dictate the color of our mesh. Now that we're using a texture we want to replace our `color` with `tex_coords`. + +```rust +#[repr(C)] +#[derive(Copy, Clone, Debug)] +struct Vertex { + position: [f32; 3], + tex_coords: [f32; 2], +} +``` + +We need to reflect these changes in the `VertexBufferDescriptor`. + +```rust +impl Vertex { + fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a> { + use std::mem; + wgpu::VertexBufferDescriptor { + stride: mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::InputStepMode::Vertex, + attributes: &[ + wgpu::VertexAttributeDescriptor { + offset: 0, + shader_location: 0, + format: wgpu::VertexFormat::Float3, + }, + wgpu::VertexAttributeDescriptor { + offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, + shader_location: 1, + // We only need to change this to reflect that tex_coords + // is only 2 floats and not 3. It's in the same position + // as color was, so nothing else needs to change + format: wgpu::VertexFormat::Float2, + }, + ] + } + } +} +``` + +Lastly we need to change `VERTICES` itself. + +```rust +const VERTICES: &[Vertex] = &[ + Vertex { position: [-0.0868241, -0.49240386, 0.0], tex_coords: [0.4131759, 0.99240386], }, // A + Vertex { position: [-0.49513406, -0.06958647, 0.0], tex_coords: [0.0048659444, 0.56958646], }, // B + Vertex { position: [-0.21918549, 0.44939706, 0.0], tex_coords: [0.28081453, 0.050602943], }, // C + Vertex { position: [0.35966998, 0.3473291, 0.0], tex_coords: [0.85967, 0.15267089], }, // D + Vertex { position: [0.44147372, -0.2347359, 0.0], tex_coords: [0.9414737, 0.7347359], }, // E +]; +``` + +## Shader time + +Our shaders will need to change inorder to support textures as well. We'll also need to remove any reference to the `color` attribute we used to have. Let's start with the vertex shader. + +```glsl +// shader.vert +#version 450 + +layout(location=0) in vec3 a_position; +// Changed +layout(location=1) in vec2 a_tex_coords; + +// Changed +layout(location=0) out vec2 v_tex_coords; + +void main() { + // Changed + v_tex_coords = a_tex_coords; + gl_Position = vec4(a_position, 1.0); +} +``` + +We need to change the fragment shader to take in `v_tex_coords`. We also need to add a reference to our texture and sampler. + +```glsl +// shader.frag +#version 450 + +// Changed +layout(location=0) in vec2 v_tex_coords; +layout(location=0) out vec4 f_color; + +// New +layout(set = 0, binding = 0) uniform texture2D t_diffuse; +layout(set = 0, binding = 1) uniform sampler s_diffuse; + +void main() { + // Changed + f_color = texture(sampler2D(t_diffuse, s_diffuse), v_tex_coords); +} +``` + +You'll notice that `t_diffuse` and `s_diffuse` are defined with the `uniform` keyword, they don't have `in` nor `out`, and the layout definition uses `set` and `binding` instead of `location`. This is because `t_diffuse` and `s_diffuse` are what we call uniforms. We won't go too deep into what a uniform is, until we talk about uniform buffers in the [cameras section](/todo). What we need to know, for now, is that `set = 0` corresponds to the 1st parameter in `set_bind_group`, `binding = 0` relates the the `binding` specified when we create the `BindGroupLayout` and `BindGroup`. + +## The results + +If we run our program now we should get the following result. + +![an upside down tree on a hexagon](./upside-down.png) + +That's weird, our tree is upside down! This is because wgpu's coordinate system has positive y values going down while texture coords have y as up. We can get our triangle right-side up by inverting the y coord of each texture coord. + +```rust +const VERTICES: &[Vertex] = &[ + Vertex { position: [-0.0868241, -0.49240386, 0.0], tex_coords: [0.4131759, 1.0 - 0.99240386], }, // A + Vertex { position: [-0.49513406, -0.06958647, 0.0], tex_coords: [0.0048659444, 1.0 - 0.56958646], }, // B + Vertex { position: [-0.21918549, 0.44939706, 0.0], tex_coords: [0.28081453, 1.0 - 0.050602943], }, // C + Vertex { position: [0.35966998, 0.3473291, 0.0], tex_coords: [0.85967, 1.0 - 0.15267089], }, // D + Vertex { position: [0.44147372, -0.2347359, 0.0], tex_coords: [0.9414737, 1.0 - 0.7347359], }, // E +]; +``` + +With that in place we now have our tree subscribed right-side up on our hexagon. + +![our happy tree as it should be](./rightside-up.png) + + + diff --git a/docs/beginner/tutorial5-textures/happy-tree.png b/docs/beginner/tutorial5-textures/happy-tree.png new file mode 100644 index 00000000..ead2f03b Binary files /dev/null and b/docs/beginner/tutorial5-textures/happy-tree.png differ diff --git a/docs/beginner/tutorial5-textures/happy-tree.xcf b/docs/beginner/tutorial5-textures/happy-tree.xcf new file mode 100644 index 00000000..4b42ae66 Binary files /dev/null and b/docs/beginner/tutorial5-textures/happy-tree.xcf differ diff --git a/docs/beginner/tutorial5-textures/rightside-up.png b/docs/beginner/tutorial5-textures/rightside-up.png new file mode 100644 index 00000000..0785c744 Binary files /dev/null and b/docs/beginner/tutorial5-textures/rightside-up.png differ diff --git a/docs/beginner/tutorial5-textures/upside-down.png b/docs/beginner/tutorial5-textures/upside-down.png new file mode 100644 index 00000000..e6d32bf2 Binary files /dev/null and b/docs/beginner/tutorial5-textures/upside-down.png differ diff --git a/docs/todo.md b/docs/todo.md new file mode 100644 index 00000000..62789501 --- /dev/null +++ b/docs/todo.md @@ -0,0 +1,11 @@ +# Coming Soon! + +This section has not yet been completed. + + + + \ No newline at end of file