strafe-client/src/main.rs

987 lines
32 KiB
Rust
Raw Normal View History

2023-09-01 05:47:55 +00:00
use std::{borrow::Cow, time::Instant};
2023-08-30 01:20:58 +00:00
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
2023-09-22 22:21:13 +00:00
use model::{Vertex,ModelData,ModelInstance};
2023-08-30 01:20:58 +00:00
2023-09-22 22:19:44 +00:00
mod body;
2023-09-22 22:21:13 +00:00
mod model;
2023-09-22 22:19:44 +00:00
mod zeroes;
mod framework;
2023-09-23 02:41:27 +00:00
mod primitives;
2023-09-22 22:19:44 +00:00
mod instruction;
mod load_roblox;
2023-08-30 01:20:58 +00:00
struct Entity {
2023-09-06 21:39:44 +00:00
index_count: u32,
index_buf: wgpu::Buffer,
2023-08-30 01:20:58 +00:00
}
struct ModelGraphics {
2023-09-21 20:02:01 +00:00
instances: Vec<ModelInstance>,
2023-09-06 21:39:44 +00:00
vertex_buf: wgpu::Buffer,
entities: Vec<Entity>,
bind_group: wgpu::BindGroup,
model_buf: wgpu::Buffer,
2023-09-05 21:58:18 +00:00
}
2023-08-30 01:20:58 +00:00
// Note: we use the Y=up coordinate space in this example.
struct Camera {
2023-09-06 21:39:44 +00:00
screen_size: (u32, u32),
offset: glam::Vec3,
fov: f32,
yaw: f32,
pitch: f32,
controls: u32,
2023-08-30 01:20:58 +00:00
}
2023-08-31 02:13:23 +00:00
const CONTROL_MOVEFORWARD:u32 = 0b00000001;
const CONTROL_MOVEBACK:u32 = 0b00000010;
const CONTROL_MOVERIGHT:u32 = 0b00000100;
const CONTROL_MOVELEFT:u32 = 0b00001000;
const CONTROL_MOVEUP:u32 = 0b00010000;
const CONTROL_MOVEDOWN:u32 = 0b00100000;
2023-08-31 07:56:00 +00:00
const CONTROL_JUMP:u32 = 0b01000000;
2023-09-01 05:48:17 +00:00
const CONTROL_ZOOM:u32 = 0b10000000;
2023-08-31 02:13:23 +00:00
const FORWARD_DIR:glam::Vec3 = glam::Vec3::new(0.0,0.0,-1.0);
const RIGHT_DIR:glam::Vec3 = glam::Vec3::new(1.0,0.0,0.0);
const UP_DIR:glam::Vec3 = glam::Vec3::new(0.0,1.0,0.0);
fn get_control_dir(controls: u32) -> glam::Vec3{
2023-09-06 21:39:44 +00:00
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::new(0.0,0.0,0.0);
if controls & CONTROL_MOVEFORWARD == CONTROL_MOVEFORWARD {
control_dir+=FORWARD_DIR;
}
if controls & CONTROL_MOVEBACK == CONTROL_MOVEBACK {
control_dir+=-FORWARD_DIR;
}
if controls & CONTROL_MOVELEFT == CONTROL_MOVELEFT {
control_dir+=-RIGHT_DIR;
}
if controls & CONTROL_MOVERIGHT == CONTROL_MOVERIGHT {
control_dir+=RIGHT_DIR;
}
if controls & CONTROL_MOVEUP == CONTROL_MOVEUP {
control_dir+=UP_DIR;
}
if controls & CONTROL_MOVEDOWN == CONTROL_MOVEDOWN {
control_dir+=-UP_DIR;
}
return control_dir
2023-08-31 02:13:23 +00:00
}
2023-08-30 01:20:58 +00:00
2023-09-06 21:39:44 +00:00
#[inline]
fn perspective_rh(fov_y_slope: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
//glam_assert!(z_near > 0.0 && z_far > 0.0);
let r = z_far / (z_near - z_far);
glam::Mat4::from_cols(
glam::Vec4::new(1.0/(fov_y_slope * aspect_ratio), 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, r, -1.0),
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
)
}
2023-09-01 05:47:55 +00:00
2023-08-30 01:20:58 +00:00
impl Camera {
2023-09-08 18:33:16 +00:00
fn to_uniform_data(&self, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
2023-09-06 21:39:44 +00:00
let aspect = self.screen_size.0 as f32 / self.screen_size.1 as f32;
let fov = if self.controls&CONTROL_ZOOM==0 {
self.fov
}else{
self.fov/5.0
};
let proj = perspective_rh(fov, aspect, 0.5, 1000.0);
let proj_inv = proj.inverse();
2023-09-08 18:33:16 +00:00
let view = glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.yaw, self.pitch, 0f32);
2023-09-06 21:39:44 +00:00
let view_inv = view.inverse();
let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
raw
}
2023-08-30 01:20:58 +00:00
}
2023-09-21 05:36:42 +00:00
pub struct GraphicsSamplers{
repeat: wgpu::Sampler,
}
pub struct GraphicsBindGroupLayouts{
model: wgpu::BindGroupLayout,
}
2023-08-30 01:20:58 +00:00
pub struct GraphicsBindGroups {
camera: wgpu::BindGroup,
skybox_texture: wgpu::BindGroup,
}
pub struct GraphicsPipelines {
skybox: wgpu::RenderPipeline,
model: wgpu::RenderPipeline,
}
pub struct GraphicsData {
2023-09-08 18:33:16 +00:00
start_time: std::time::Instant,
2023-09-06 21:39:44 +00:00
camera: Camera,
2023-09-22 22:19:44 +00:00
physics: body::PhysicsState,
pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups,
2023-09-21 05:36:42 +00:00
bind_group_layouts: GraphicsBindGroupLayouts,
samplers: GraphicsSamplers,
temp_squid_texture_view: wgpu::TextureView,
2023-09-06 21:39:44 +00:00
camera_buf: wgpu::Buffer,
models: Vec<ModelGraphics>,
2023-09-06 21:39:44 +00:00
depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt,
2023-08-30 01:20:58 +00:00
}
impl GraphicsData {
2023-09-06 21:39:44 +00:00
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
fn create_depth_texture(
config: &wgpu::SurfaceConfiguration,
device: &wgpu::Device,
) -> wgpu::TextureView {
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: Self::DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
label: None,
view_formats: &[],
});
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
}
2023-09-21 05:36:42 +00:00
2023-09-21 21:11:41 +00:00
fn generate_model_physics(&mut self,modeldatas:&Vec<ModelData>){
self.physics.models.append(&mut modeldatas.iter().map(|m|
//make aabb and run vertices to get realistic bounds
m.instances.iter().map(|t|body::ModelPhysics::new(t.model_transform))
2023-09-21 21:11:41 +00:00
).flatten().collect());
println!("Physics Objects: {}",self.physics.models.len());
2023-09-21 21:11:41 +00:00
}
2023-09-23 02:41:27 +00:00
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,mut modeldatas:Vec<ModelData>,textures:Vec<String>){
//generate texture view per texture
//idk how to do this gooder lol
let mut double_map=std::collections::HashMap::<u32,u32>::new();
let mut texture_views:Vec<wgpu::TextureView>=Vec::with_capacity(textures.len());
for (i,t) in textures.iter().enumerate(){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",t))){
let image = ddsfile::Dds::read(&mut file).unwrap();
let size = wgpu::Extent3d {
width: image.get_width()/4*4,//floor(w,4), should be ceil(w,4)
height: image.get_height()/4*4,
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bc7RgbaUnorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",i).as_str()),
view_formats: &[],
},
&image.data,
);
double_map.insert(i as u32, texture_views.len() as u32);
texture_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",i).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
}));
}
}
2023-09-21 05:36:42 +00:00
//drain the modeldata vec so entities can be /moved/ to models.entities
let mut instance_count=0;
2023-09-27 00:54:52 +00:00
let uniform_buffer_binding_size=<GraphicsData as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize;
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
2023-09-21 05:36:42 +00:00
self.models.reserve(modeldatas.len());
for (i,modeldata) in modeldatas.drain(..).enumerate() {
2023-09-23 02:41:27 +00:00
let n_instances=modeldata.instances.len();
2023-09-27 00:54:52 +00:00
instance_count+=n_instances;
for instances_chunk in modeldata.instances.rchunks(chunk_size){
let model_uniforms = get_instances_buffer_data(instances_chunk);
2023-09-23 02:41:27 +00:00
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(format!("Model{} Buf",i).as_str()),
contents: bytemuck::cast_slice(&model_uniforms),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let texture_view=match modeldata.texture{
Some(texture_id)=>{
match double_map.get(&texture_id){
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
None=>&self.temp_squid_texture_view,
}
2023-09-21 05:36:42 +00:00
},
2023-09-23 02:41:27 +00:00
None=>&self.temp_squid_texture_view,
};
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.bind_group_layouts.model,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: model_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
},
],
label: Some(format!("Model{} Bind Group",i).as_str()),
});
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex"),
contents: bytemuck::cast_slice(&modeldata.vertices),
usage: wgpu::BufferUsages::VERTEX,
});
//all of these are being moved here
self.models.push(ModelGraphics{
2023-09-27 00:54:52 +00:00
instances:instances_chunk.to_vec(),
2023-09-23 02:41:27 +00:00
vertex_buf,
entities: modeldata.entities.iter().map(|indices|{
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index"),
contents: bytemuck::cast_slice(&indices),
usage: wgpu::BufferUsages::INDEX,
});
Entity {
index_buf,
index_count: indices.len() as u32,
}
}).collect(),
bind_group: model_bind_group,
model_buf,
});
}
2023-09-21 05:36:42 +00:00
}
println!("Graphics Objects: {}",self.models.len());
println!("Graphics Instances: {}",instance_count);
2023-09-21 05:36:42 +00:00
}
2023-08-30 01:20:58 +00:00
}
const MODEL_BUFFER_SIZE:usize=4*4 + 2*2 + 2+2 + 4;//let size=std::mem::size_of::<ModelInstance>();
2023-09-27 00:54:52 +00:00
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
fn get_instances_buffer_data(instances:&[ModelInstance]) -> Vec<f32> {
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
2023-09-21 20:02:01 +00:00
for (i,mi) in instances.iter().enumerate(){
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
//model_transform
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&glam::Mat4::from(mi.model_transform))[..]);
//texture_matrix
raw.extend_from_slice(&AsRef::<[f32; 2*2]>::as_ref(&mi.texture_transform.matrix2)[..]);
//texture_offset
raw.extend_from_slice(AsRef::<[f32; 2]>::as_ref(&mi.texture_transform.translation));
raw.extend_from_slice(&[0.0,0.0]);
//color
2023-09-21 20:02:01 +00:00
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color));
2023-09-20 20:03:25 +00:00
raw.append(&mut v);
}
2023-09-06 21:39:44 +00:00
raw
2023-09-01 21:59:42 +00:00
}
2023-09-22 22:19:44 +00:00
impl framework::Example for GraphicsData {
2023-09-06 21:39:44 +00:00
fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
| wgpu::Features::TEXTURE_COMPRESSION_BC
}
fn required_limits() -> wgpu::Limits {
wgpu::Limits::default() //framework.rs was using goofy limits that caused me a multi-day headache
}
2023-09-06 21:39:44 +00:00
fn init(
config: &wgpu::SurfaceConfiguration,
_adapter: &wgpu::Adapter,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Self {
2023-09-23 02:41:27 +00:00
let unit_cube=primitives::the_unit_cube_lol();
let mut modeldatas = Vec::<ModelData>::new();
2023-09-23 02:41:27 +00:00
modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
modeldatas.append(&mut model::generate_modeldatas(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),ModelData::COLOR_FLOATS_WHITE));
modeldatas.append(&mut model::generate_modeldatas(unit_cube.clone(),ModelData::COLOR_FLOATS_WHITE));
2023-09-06 21:39:44 +00:00
println!("models.len = {:?}", modeldatas.len());
2023-09-21 20:02:01 +00:00
modeldatas[0].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)),
texture_transform:glam::Affine2::IDENTITY,
2023-09-21 20:02:01 +00:00
color:ModelData::COLOR_VEC4_WHITE,
});
//quad monkeys
2023-09-21 20:02:01 +00:00
modeldatas[1].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)),
texture_transform:glam::Affine2::IDENTITY,
2023-09-21 20:02:01 +00:00
color:ModelData::COLOR_VEC4_WHITE,
});
modeldatas[1].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)),
texture_transform:glam::Affine2::IDENTITY,
2023-09-21 20:02:01 +00:00
color:glam::vec4(1.0,0.0,0.0,1.0),
});
modeldatas[1].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)),
texture_transform:glam::Affine2::IDENTITY,
2023-09-21 20:02:01 +00:00
color:glam::vec4(0.0,1.0,0.0,1.0),
});
modeldatas[1].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)),
texture_transform:glam::Affine2::IDENTITY,
2023-09-21 20:02:01 +00:00
color:glam::vec4(0.0,0.0,1.0,1.0),
});
//teapot
2023-09-21 20:02:01 +00:00
modeldatas[2].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(-10.,5.,10.)),
2023-09-27 00:01:17 +00:00
texture_transform:glam::Affine2::from_scale(glam::vec2(2.0,2.0)),
2023-09-21 20:02:01 +00:00
color:ModelData::COLOR_VEC4_WHITE,
});
//ground
2023-09-21 20:02:01 +00:00
modeldatas[3].instances.push(ModelInstance{
model_transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)),
texture_transform:glam::Affine2::IDENTITY,
2023-09-21 20:02:01 +00:00
color:ModelData::COLOR_VEC4_WHITE,
});
2023-09-06 21:39:44 +00:00
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2023-09-06 21:39:44 +00:00
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: &[
2023-09-06 21:39:44 +00:00
wgpu::BindGroupLayoutEntry {
binding: 0,
2023-09-06 21:39:44 +00:00
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,
2023-09-06 21:39:44 +00:00
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"),
2023-09-06 21:39:44 +00:00
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
2023-09-06 21:39:44 +00:00
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
2023-09-06 21:39:44 +00:00
],
});
let clamp_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Clamp Sampler"),
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 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()
});
2023-09-06 21:39:44 +00:00
// Create the render pipeline
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
let camera = Camera {
screen_size: (config.width, config.height),
2023-09-19 02:47:15 +00:00
offset: glam::Vec3::new(0.0,4.5-2.5,0.0),
2023-09-06 21:39:44 +00:00
fov: 1.0, //fov_slope = tan(fov_y/2)
pitch: 0.0,
yaw: 0.0,
controls:0,
2023-09-08 18:33:16 +00:00
};
2023-09-22 22:19:44 +00:00
let physics = body::PhysicsState {
body: body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
2023-09-08 18:33:16 +00:00
time: 0,
tick: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
2023-09-18 23:04:02 +00:00
gravity: glam::vec3(0.0,-100.0,0.0),
2023-09-19 04:10:07 +00:00
friction: 1.2,
walk_accel: 90.0,
2023-09-08 18:33:16 +00:00
mv: 2.7,
2023-09-18 23:04:08 +00:00
grounded: false,
2023-09-08 18:33:20 +00:00
jump_trying: false,
2023-09-09 03:14:18 +00:00
temp_control_dir: glam::Vec3::ZERO,
2023-09-06 21:39:44 +00:00
walkspeed: 18.0,
2023-09-18 20:44:43 +00:00
contacts: std::collections::HashSet::new(),
2023-09-21 21:11:41 +00:00
models: Vec::new(),
2023-09-22 22:19:44 +00:00
walk: body::WalkState::new(),
2023-09-18 20:56:23 +00:00
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
2023-09-06 21:39:44 +00:00
};
2023-09-08 18:33:16 +00:00
2023-09-21 00:01:57 +00:00
//load textures
let device_features = device.features();
2023-09-21 00:01:06 +00:00
let skybox_texture_view={
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
log::info!("Using ASTC");
wgpu::TextureFormat::Astc {
block: AstcBlock::B4x4,
channel: AstcChannel::UnormSrgb,
}
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
log::info!("Using ETC2");
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
log::info!("Using BC");
wgpu::TextureFormat::Bc1RgbaUnormSrgb
} else {
log::info!("Using plain");
wgpu::TextureFormat::Bgra8UnormSrgb
};
2023-09-22 22:20:41 +00:00
let bytes = match skybox_format {
wgpu::TextureFormat::Astc {
block: AstcBlock::B4x4,
channel: AstcChannel::UnormSrgb,
} => &include_bytes!("../images/astc.dds")[..],
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
_ => unreachable!(),
};
let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
2023-09-21 00:01:06 +00:00
let size = wgpu::Extent3d {
2023-09-22 22:20:41 +00:00
width: skybox_image.get_width(),
height: skybox_image.get_height(),
2023-09-21 00:01:06 +00:00
depth_or_array_layers: 6,
};
2023-09-21 00:01:06 +00:00
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
2023-09-21 00:01:06 +00:00
log::debug!(
"Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu",
skybox_format,
2023-09-22 22:20:41 +00:00
size.width,
size.height,
2023-09-21 00:01:06 +00:00
max_mips,
);
let skybox_texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: skybox_format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some("Skybox Texture"),
view_formats: &[],
},
&skybox_image.data,
);
skybox_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("Skybox Texture View"),
dimension: Some(wgpu::TextureViewDimension::Cube),
..wgpu::TextureViewDescriptor::default()
})
};
2023-09-06 21:39:44 +00:00
2023-09-21 00:01:57 +00:00
//squid
let squid_texture_view={
2023-09-22 03:56:24 +00:00
let bytes = include_bytes!("../images/squid.dds");
2023-09-21 18:56:03 +00:00
2023-09-22 03:56:24 +00:00
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
2023-09-21 18:56:03 +00:00
2023-09-21 00:01:57 +00:00
let size = wgpu::Extent3d {
2023-09-21 18:56:03 +00:00
width: image.get_width(),
height: image.get_height(),
2023-09-21 00:01:57 +00:00
depth_or_array_layers: 1,
};
let layer_size = wgpu::Extent3d {
depth_or_array_layers: 1,
..size
};
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
size,
mip_level_count: max_mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bc7RgbaUnorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some("Squid Texture"),
view_formats: &[],
},
&image.data,
);
texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("Squid Texture View"),
dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default()
})
};
2023-09-06 21:39:44 +00:00
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[
&camera_bind_group_layout,
&model_bind_group_layout,
&skybox_texture_bind_group_layout,
],
2023-09-06 21:39:44 +00:00
push_constant_ranges: &[],
});
// Create the render pipelines
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Sky Pipeline"),
2023-09-06 21:39:44 +00:00
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_sky",
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_sky",
targets: &[Some(config.view_formats[0].into())],
}),
primitive: wgpu::PrimitiveState {
front_face: wgpu::FrontFace::Cw,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: Self::DEPTH_FORMAT,
depth_write_enabled: false,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState::default(),
multiview: None,
});
let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Model Pipeline"),
2023-09-06 21:39:44 +00:00
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_entity_texture",
2023-09-06 21:39:44 +00:00
buffers: &[wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
2023-09-21 20:02:01 +00:00
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32x3, 3 => Float32x4],
2023-09-06 21:39:44 +00:00
}],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_entity_texture",
2023-09-06 21:39:44 +00:00
targets: &[Some(config.view_formats[0].into())],
}),
primitive: wgpu::PrimitiveState {
front_face: wgpu::FrontFace::Cw,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: Self::DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState::default(),
multiview: None,
});
let camera_uniforms = camera.to_uniform_data(physics.body.extrapolated_position(0));
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera"),
contents: bytemuck::cast_slice(&camera_uniforms),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2023-09-06 21:39:44 +00:00
});
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &camera_bind_group_layout,
2023-09-06 21:39:44 +00:00
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: camera_buf.as_entire_binding(),
},
],
label: Some("Camera"),
});
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &skybox_texture_bind_group_layout,
entries: &[
2023-09-06 21:39:44 +00:00
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&skybox_texture_view),
2023-09-06 21:39:44 +00:00
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&clamp_sampler),
2023-09-06 21:39:44 +00:00
},
],
label: Some("Sky Texture"),
2023-09-06 21:39:44 +00:00
});
let depth_view = Self::create_depth_texture(config, device);
2023-09-21 05:36:42 +00:00
let mut graphics=GraphicsData {
2023-09-08 18:33:16 +00:00
start_time: Instant::now(),
2023-09-06 21:39:44 +00:00
camera,
2023-09-08 18:33:16 +00:00
physics,
pipelines:GraphicsPipelines{
skybox:sky_pipeline,
model:model_pipeline
},
bind_groups:GraphicsBindGroups{
camera:camera_bind_group,
skybox_texture:skybox_texture_bind_group,
},
2023-09-06 21:39:44 +00:00
camera_buf,
2023-09-21 05:36:42 +00:00
models: Vec::new(),
2023-09-06 21:39:44 +00:00
depth_view,
staging_belt: wgpu::util::StagingBelt::new(0x100),
2023-09-21 05:36:42 +00:00
bind_group_layouts: GraphicsBindGroupLayouts { model: model_bind_group_layout },
samplers: GraphicsSamplers { repeat: repeat_sampler },
temp_squid_texture_view: squid_texture_view,
};
2023-09-21 21:11:41 +00:00
graphics.generate_model_physics(&modeldatas);
2023-09-23 02:41:27 +00:00
graphics.generate_model_graphics(&device,&queue,modeldatas,Vec::new());
2023-09-21 05:36:42 +00:00
return graphics;
2023-09-06 21:39:44 +00:00
}
#[allow(clippy::single_match)]
2023-09-23 02:41:27 +00:00
fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
2023-09-21 05:36:42 +00:00
//nothing atm
2023-09-06 21:39:44 +00:00
match event {
2023-09-21 05:36:42 +00:00
winit::event::WindowEvent::DroppedFile(path) => {
println!("opening file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
//
2023-09-23 02:41:27 +00:00
if let Some(Ok((modeldatas,textures,spawn_point)))={
if &first_8==b"<roblox!"{
if let Ok(dom) = rbx_binary::from_reader(input){
2023-09-23 02:41:27 +00:00
Some(load_roblox::generate_modeldatas_roblox(dom))
}else{
None
}
2023-09-26 21:26:05 +00:00
}else if &first_8==b"<roblox "{
if let Ok(dom) = rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()){
2023-09-23 02:41:27 +00:00
Some(load_roblox::generate_modeldatas_roblox(dom))
2023-09-26 21:26:05 +00:00
}else{
None
}
//}else if &first_8[0..4]==b"VBSP"{
// self.generate_modeldatas_valve(input)
}else{
None
}
}{
//if generate_modeldatas succeeds, clear the previous ones
self.models.clear();
self.physics.models.clear();
self.generate_model_physics(&modeldatas);
2023-09-23 02:41:27 +00:00
self.generate_model_graphics(device,queue,modeldatas,textures);
//manual reset
let time=self.physics.time;
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::SetPosition(spawn_point),
})
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed ro read first 8 bytes and seek back to beginning of file.");
}
2023-09-21 05:36:42 +00:00
}else{
println!("Could not open file");
}
},
2023-09-06 21:39:44 +00:00
winit::event::WindowEvent::KeyboardInput {
input:
winit::event::KeyboardInput {
state,
virtual_keycode: Some(keycode),
..
},
..
} => {
match (state,keycode) {
(k,winit::event::VirtualKeyCode::W) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEFORWARD,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEFORWARD,
}
(k,winit::event::VirtualKeyCode::A) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVELEFT,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVELEFT,
}
(k,winit::event::VirtualKeyCode::S) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEBACK,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEBACK,
}
(k,winit::event::VirtualKeyCode::D) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVERIGHT,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVERIGHT,
}
(k,winit::event::VirtualKeyCode::E) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEUP,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEUP,
}
(k,winit::event::VirtualKeyCode::Q) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_MOVEDOWN,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_MOVEDOWN,
}
(k,winit::event::VirtualKeyCode::Space) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_JUMP,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_JUMP,
}
(k,winit::event::VirtualKeyCode::Z) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_ZOOM,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_ZOOM,
}
_ => (),
}
}
_ => {}
}
}
fn move_mouse(&mut self, delta: (f64,f64)) {
2023-09-07 02:35:32 +00:00
self.camera.pitch=(self.camera.pitch as f64+delta.1/-2048.) as f32;
self.camera.yaw=(self.camera.yaw as f64+delta.0/-2048.) as f32;
2023-09-06 21:39:44 +00:00
}
fn resize(
&mut self,
config: &wgpu::SurfaceConfiguration,
device: &wgpu::Device,
_queue: &wgpu::Queue,
) {
self.depth_view = Self::create_depth_texture(config, device);
self.camera.screen_size = (config.width, config.height);
}
fn render(
&mut self,
view: &wgpu::TextureView,
device: &wgpu::Device,
queue: &wgpu::Queue,
2023-09-22 22:19:44 +00:00
_spawner: &framework::Spawner,
2023-09-06 21:39:44 +00:00
) {
2023-09-19 01:31:04 +00:00
let camera_mat=glam::Mat3::from_rotation_y(self.camera.yaw);
2023-09-06 21:39:44 +00:00
let control_dir=camera_mat*get_control_dir(self.camera.controls&(CONTROL_MOVELEFT|CONTROL_MOVERIGHT|CONTROL_MOVEFORWARD|CONTROL_MOVEBACK)).normalize_or_zero();
2023-09-08 18:33:16 +00:00
let time=self.start_time.elapsed().as_nanos() as i64;
2023-09-19 06:57:42 +00:00
self.physics.run(time);
//ALL OF THIS IS TOTALLY WRONG!!!
2023-09-19 04:10:07 +00:00
let walk_target_velocity=self.physics.walkspeed*control_dir;
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
if self.physics.grounded&&walk_target_velocity!=self.physics.walk.target_velocity {
2023-09-22 22:19:44 +00:00
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
2023-09-19 07:00:14 +00:00
time,
2023-09-22 22:19:44 +00:00
instruction:body::PhysicsInstruction::SetWalkTargetVelocity(walk_target_velocity)
2023-09-19 04:10:07 +00:00
});
}
if control_dir!=self.physics.temp_control_dir {
2023-09-22 22:19:44 +00:00
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
2023-09-22 22:19:44 +00:00
instruction:body::PhysicsInstruction::SetControlDir(control_dir)
});
}
2023-09-06 21:39:44 +00:00
2023-09-19 06:57:42 +00:00
self.physics.jump_trying=self.camera.controls&CONTROL_JUMP!=0;
2023-09-19 01:06:51 +00:00
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
if self.physics.grounded&&self.physics.jump_trying {
//scroll will be implemented with InputInstruction::Jump(true) but it blocks setting self.jump_trying=true
2023-09-22 22:19:44 +00:00
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
2023-09-19 07:00:14 +00:00
time,
2023-09-22 22:19:44 +00:00
instruction:body::PhysicsInstruction::Jump
2023-09-19 01:06:51 +00:00
});
}
2023-09-06 21:39:44 +00:00
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// update rotation
2023-09-09 03:14:18 +00:00
let camera_uniforms = self.camera.to_uniform_data(self.physics.body.extrapolated_position(time));
2023-09-06 21:39:44 +00:00
self.staging_belt
.write_buffer(
&mut encoder,
&self.camera_buf,
0,
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device,
)
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
//This code only needs to run when the uniforms change
for model in self.models.iter() {
2023-09-21 20:02:01 +00:00
let model_uniforms = get_instances_buffer_data(&model.instances);
2023-09-06 21:39:44 +00:00
self.staging_belt
.write_buffer(
&mut encoder,
&model.model_buf,//description of where data will be written when command is executed
0,//offset in staging belt?
wgpu::BufferSize::new((model_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device,
)
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
}
self.staging_belt.finish();
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
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,
}),
store: true,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: false,
}),
stencil_ops: None,
}),
});
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(2, &self.bind_groups.skybox_texture, &[]);
2023-09-06 21:39:44 +00:00
rpass.set_pipeline(&self.pipelines.model);
2023-09-06 21:39:44 +00:00
for model in self.models.iter() {
rpass.set_bind_group(1, &model.bind_group, &[]);
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
for entity in model.entities.iter() {
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
2023-09-21 20:02:01 +00:00
rpass.draw_indexed(0..entity.index_count, 0, 0..model.instances.len() as u32);
2023-09-06 21:39:44 +00:00
}
}
rpass.set_pipeline(&self.pipelines.skybox);
2023-09-06 21:39:44 +00:00
rpass.draw(0..3, 0..1);
}
queue.submit(std::iter::once(encoder.finish()));
self.staging_belt.recall();
}
2023-08-30 01:20:58 +00:00
}
2023-07-14 23:49:01 +00:00
fn main() {
2023-09-22 22:19:44 +00:00
framework::run::<GraphicsData>(
2023-09-06 21:39:44 +00:00
format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION")
).as_str()
);
2023-08-30 01:20:58 +00:00
}