split main bind group, rename everything, organize GraphicsData

This commit is contained in:
Quaternions 2023-09-20 15:57:06 -07:00
parent acb658f3e9
commit fb4a5efa14
2 changed files with 175 additions and 97 deletions

View File

@ -113,20 +113,29 @@ impl Camera {
} }
} }
pub struct Skybox { pub struct GraphicsBindGroups {
camera: wgpu::BindGroup,
skybox_texture: wgpu::BindGroup,
}
pub struct GraphicsPipelines {
skybox: wgpu::RenderPipeline,
model: wgpu::RenderPipeline,
}
pub struct GraphicsData {
start_time: std::time::Instant, start_time: std::time::Instant,
camera: Camera, camera: Camera,
physics: strafe_client::body::PhysicsState, physics: strafe_client::body::PhysicsState,
sky_pipeline: wgpu::RenderPipeline, pipelines: GraphicsPipelines,
entity_pipeline: wgpu::RenderPipeline, bind_groups: GraphicsBindGroups,
main_bind_group: wgpu::BindGroup,
camera_buf: wgpu::Buffer, camera_buf: wgpu::Buffer,
models: Vec<ModelGraphics>, models: Vec<ModelGraphics>,
depth_view: wgpu::TextureView, depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt, staging_belt: wgpu::util::StagingBelt,
} }
impl Skybox { impl GraphicsData {
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus; const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
fn create_depth_texture( fn create_depth_texture(
@ -211,7 +220,7 @@ fn add_obj(device:&wgpu::Device,modeldatas:& mut Vec<ModelData>,data:obj::ObjDat
} }
} }
impl strafe_client::framework::Example for Skybox { impl strafe_client::framework::Example for GraphicsData {
fn optional_features() -> wgpu::Features { fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2 | wgpu::Features::TEXTURE_COMPRESSION_ETC2
@ -258,8 +267,44 @@ impl strafe_client::framework::Example for Skybox {
modeldatas[2].transforms[0]=glam::Mat4::from_translation(glam::vec3(-10.,5.,10.)); modeldatas[2].transforms[0]=glam::Mat4::from_translation(glam::vec3(-10.,5.,10.));
modeldatas[3].transforms[0]=glam::Mat4::from_translation(glam::vec3(0.,0.,0.))*glam::Mat4::from_scale(glam::vec3(160.0, 1.0, 160.0)); modeldatas[3].transforms[0]=glam::Mat4::from_translation(glam::vec3(0.,0.,0.))*glam::Mat4::from_scale(glam::vec3(160.0, 1.0, 160.0));
let main_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: None,
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let skybox_texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Skybox Texture Bind Group Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
multisampled: false,
view_dimension: wgpu::TextureViewDimension::Cube,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Model Bind Group Layout"),
entries: &[ entries: &[
wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
@ -277,7 +322,7 @@ impl strafe_client::framework::Example for Skybox {
ty: wgpu::BindingType::Texture { ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true }, sample_type: wgpu::TextureSampleType::Float { filterable: true },
multisampled: false, multisampled: false,
view_dimension: wgpu::TextureViewDimension::Cube, view_dimension: wgpu::TextureViewDimension::D2,
}, },
count: None, count: None,
}, },
@ -289,20 +334,26 @@ impl strafe_client::framework::Example for Skybox {
}, },
], ],
}); });
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Model"), let clamp_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
entries: &[ label: Some("Clamp Sampler"),
wgpu::BindGroupLayoutEntry { address_mode_u: wgpu::AddressMode::ClampToEdge,
binding: 0, address_mode_v: wgpu::AddressMode::ClampToEdge,
visibility: wgpu::ShaderStages::VERTEX, address_mode_w: wgpu::AddressMode::ClampToEdge,
ty: wgpu::BindingType::Buffer { mag_filter: wgpu::FilterMode::Linear,
ty: wgpu::BufferBindingType::Uniform, min_filter: wgpu::FilterMode::Linear,
has_dynamic_offset: false, mipmap_filter: wgpu::FilterMode::Linear,
min_binding_size: None, ..Default::default()
}, });
count: None, let repeat_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
}, label: Some("Repeat Sampler"),
], address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Linear,
..Default::default()
}); });
// Create the render pipeline // Create the render pipeline
@ -362,6 +413,14 @@ impl strafe_client::framework::Example for Skybox {
binding: 0, binding: 0,
resource: model_buf.as_entire_binding(), resource: model_buf.as_entire_binding(),
}, },
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&squid_texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&repeat_sampler),
},
], ],
label: Some(format!("ModelGraphics{}",i).as_str()), label: Some(format!("ModelGraphics{}",i).as_str()),
}); });
@ -377,13 +436,17 @@ impl strafe_client::framework::Example for Skybox {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None, label: None,
bind_group_layouts: &[&main_bind_group_layout, &model_bind_group_layout], bind_group_layouts: &[
&camera_bind_group_layout,
&model_bind_group_layout,
&skybox_texture_bind_group_layout,
],
push_constant_ranges: &[], push_constant_ranges: &[],
}); });
// Create the render pipelines // Create the render pipelines
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Sky"), label: Some("Sky Pipeline"),
layout: Some(&pipeline_layout), layout: Some(&pipeline_layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
@ -409,12 +472,12 @@ impl strafe_client::framework::Example for Skybox {
multisample: wgpu::MultisampleState::default(), multisample: wgpu::MultisampleState::default(),
multiview: None, multiview: None,
}); });
let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Entity"), label: Some("Model Pipeline"),
layout: Some(&pipeline_layout), layout: Some(&pipeline_layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: "vs_entity", entry_point: "vs_entity_texture",
buffers: &[wgpu::VertexBufferLayout { buffers: &[wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress, array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex, step_mode: wgpu::VertexStepMode::Vertex,
@ -423,7 +486,7 @@ impl strafe_client::framework::Example for Skybox {
}, },
fragment: Some(wgpu::FragmentState { fragment: Some(wgpu::FragmentState {
module: &shader, module: &shader,
entry_point: "fs_entity", entry_point: "fs_entity_texture",
targets: &[Some(config.view_formats[0].into())], targets: &[Some(config.view_formats[0].into())],
}), }),
primitive: wgpu::PrimitiveState { primitive: wgpu::PrimitiveState {
@ -441,17 +504,6 @@ impl strafe_client::framework::Example for Skybox {
multiview: None, multiview: None,
}); });
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: None,
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::Linear,
mipmap_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let device_features = device.features(); let device_features = device.features();
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) { let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
@ -502,9 +554,9 @@ impl strafe_client::framework::Example for Skybox {
_ => unreachable!(), _ => unreachable!(),
}; };
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap(); let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
let texture = device.create_texture_with_data( let skybox_texture = device.create_texture_with_data(
queue, queue,
&wgpu::TextureDescriptor { &wgpu::TextureDescriptor {
size, size,
@ -513,45 +565,57 @@ impl strafe_client::framework::Example for Skybox {
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
format: skybox_format, format: skybox_format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: None, label: Some("Skybox Texture"),
view_formats: &[], view_formats: &[],
}, },
&image.data, &skybox_image.data,
); );
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor { let skybox_texture_view = skybox_texture.create_view(&wgpu::TextureViewDescriptor {
label: None, label: Some("Skybox Texture View"),
dimension: Some(wgpu::TextureViewDimension::Cube), dimension: Some(wgpu::TextureViewDimension::Cube),
..wgpu::TextureViewDescriptor::default() ..wgpu::TextureViewDescriptor::default()
}); });
let main_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &main_bind_group_layout, let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &camera_bind_group_layout,
entries: &[ entries: &[
wgpu::BindGroupEntry { wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: camera_buf.as_entire_binding(), resource: camera_buf.as_entire_binding(),
}, },
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
], ],
label: Some("Camera"), label: Some("Camera"),
}); });
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &skybox_texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&skybox_texture_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&clamp_sampler),
},
],
label: Some("Sky Texture"),
});
let depth_view = Self::create_depth_texture(config, device); let depth_view = Self::create_depth_texture(config, device);
Skybox { GraphicsData {
start_time: Instant::now(), start_time: Instant::now(),
camera, camera,
physics, physics,
sky_pipeline, pipelines:GraphicsPipelines{
entity_pipeline, skybox:sky_pipeline,
main_bind_group, model:model_pipeline
},
bind_groups:GraphicsBindGroups{
camera:camera_bind_group,
skybox_texture:skybox_texture_bind_group,
},
camera_buf, camera_buf,
models, models,
depth_view, depth_view,
@ -722,9 +786,10 @@ impl strafe_client::framework::Example for Skybox {
}), }),
}); });
rpass.set_bind_group(0, &self.main_bind_group, &[]); rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(2, &self.bind_groups.skybox_texture, &[]);
rpass.set_pipeline(&self.entity_pipeline); rpass.set_pipeline(&self.pipelines.model);
for model in self.models.iter() { for model in self.models.iter() {
rpass.set_bind_group(1, &model.bind_group, &[]); rpass.set_bind_group(1, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..)); rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
@ -735,7 +800,7 @@ impl strafe_client::framework::Example for Skybox {
} }
} }
rpass.set_pipeline(&self.sky_pipeline); rpass.set_pipeline(&self.pipelines.skybox);
rpass.draw(0..3, 0..1); rpass.draw(0..3, 0..1);
} }
@ -746,7 +811,7 @@ impl strafe_client::framework::Example for Skybox {
} }
fn main() { fn main() {
strafe_client::framework::run::<Skybox>( strafe_client::framework::run::<GraphicsData>(
format!("Strafe Client v{}", format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
).as_str() ).as_str()

View File

@ -1,9 +1,4 @@
struct SkyOutput { struct Camera {
@builtin(position) position: vec4<f32>,
@location(0) sampledir: vec3<f32>,
};
struct Data {
// from camera to screen // from camera to screen
proj: mat4x4<f32>, proj: mat4x4<f32>,
// from screen to camera // from screen to camera
@ -13,9 +8,16 @@ struct Data {
// camera position // camera position
cam_pos: vec4<f32>, cam_pos: vec4<f32>,
}; };
//group 0 is the camera
@group(0) @group(0)
@binding(0) @binding(0)
var<uniform> r_data: Data; var<uniform> camera: Camera;
struct SkyOutput {
@builtin(position) position: vec4<f32>,
@location(0) sampledir: vec3<f32>,
};
@vertex @vertex
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput { fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
@ -30,8 +32,8 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
); );
// transposition = inversion for this orthonormal matrix // transposition = inversion for this orthonormal matrix
let inv_model_view = transpose(mat3x3<f32>(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz)); let inv_model_view = transpose(mat3x3<f32>(camera.view[0].xyz, camera.view[1].xyz, camera.view[2].xyz));
let unprojected = r_data.proj_inv * pos; let unprojected = camera.proj_inv * pos;
var result: SkyOutput; var result: SkyOutput;
result.sampledir = inv_model_view * unprojected.xyz; result.sampledir = inv_model_view * unprojected.xyz;
@ -39,54 +41,65 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
return result; return result;
} }
struct EntityOutput { const MAX_ENTITY_INSTANCES=1024;
//group 1 is the model
@group(1)
@binding(0)
var<uniform> entity_transforms: array<mat4x4<f32>,MAX_ENTITY_INSTANCES>;
//var<uniform> entity_texture_transforms: array<mat3x3<f32>,MAX_ENTITY_INSTANCES>;
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
//the texture transform then maps the texture coordinates to the location of the specific texture
//how to do no texture?
@group(1)
@binding(1)
var model_texture: texture_2d<f32>;
@group(1)
@binding(2)
var model_sampler: sampler;
struct EntityOutputTexture {
@builtin(position) position: vec4<f32>, @builtin(position) position: vec4<f32>,
@location(1) texture: vec2<f32>, @location(1) texture: vec2<f32>,
@location(2) normal: vec3<f32>, @location(2) normal: vec3<f32>,
@location(3) view: vec3<f32>, @location(3) view: vec3<f32>,
}; };
const MAX_ENTITY_INSTANCES=1024;
@group(1)
@binding(0)
var<uniform> r_EntityTransform: array<mat4x4<f32>,MAX_ENTITY_INSTANCES>;
@vertex @vertex
fn vs_entity( fn vs_entity_texture(
@builtin(instance_index) instance: u32, @builtin(instance_index) instance: u32,
@location(0) pos: vec3<f32>, @location(0) pos: vec3<f32>,
@location(1) texture: vec2<f32>, @location(1) texture: vec2<f32>,
@location(2) normal: vec3<f32>, @location(2) normal: vec3<f32>,
) -> EntityOutput { ) -> EntityOutputTexture {
var position: vec4<f32> = r_EntityTransform[instance] * vec4<f32>(pos, 1.0); var position: vec4<f32> = entity_transforms[instance] * vec4<f32>(pos, 1.0);
var result: EntityOutput; var result: EntityOutputTexture;
result.normal = (r_EntityTransform[instance] * vec4<f32>(normal, 0.0)).xyz; result.normal = (entity_transforms[instance] * vec4<f32>(normal, 0.0)).xyz;
result.texture=texture; result.texture=texture;//(entity_texture_transforms[instance] * vec3<f32>(texture, 1.0)).xy;
result.view = position.xyz - r_data.cam_pos.xyz; result.view = position.xyz - camera.cam_pos.xyz;
result.position = r_data.proj * r_data.view * position; result.position = camera.proj * camera.view * position;
return result; return result;
} }
@group(0) //group 2 is the skybox texture
@group(2)
@binding(0)
var cube_texture: texture_cube<f32>;
@group(2)
@binding(1) @binding(1)
var r_texture: texture_cube<f32>; var cube_sampler: sampler;
@group(0)
@binding(2)
var r_sampler: sampler;
@fragment @fragment
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> { fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
return textureSample(r_texture, r_sampler, vertex.sampledir); return textureSample(cube_texture, model_sampler, vertex.sampledir);
} }
@fragment @fragment
fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> { fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
let incident = normalize(vertex.view); let incident = normalize(vertex.view);
let normal = normalize(vertex.normal); let normal = normalize(vertex.normal);
let d = dot(normal, incident); let d = dot(normal, incident);
let reflected = incident - 2.0 * d * normal; let reflected = incident - 2.0 * d * normal;
let dir = vec3<f32>(-1.0)+2.0*vec3<f32>(vertex.texture.x,0.0,vertex.texture.y); let fragment_color = textureSample(model_texture, model_sampler, vertex.texture).rgb;
let texture_color = textureSample(r_texture, r_sampler, dir).rgb; let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
let reflected_color = textureSample(r_texture, r_sampler, reflected).rgb; return vec4<f32>(mix(vec3<f32>(0.1) + 0.5 * reflected_color,fragment_color,1.0-pow(1.0-abs(d),2.0)), 1.0);
return vec4<f32>(mix(vec3<f32>(0.1) + 0.5 * reflected_color,texture_color,1.0-pow(1.0-abs(d),2.0)), 1.0);
} }