Compare commits

...

5 commits

Author SHA1 Message Date
griffi-gh 3f768a8318 do rpass in world.rs 2024-05-05 15:42:25 +02:00
griffi-gh baf037d4a5 use Arc<Window> instead of create_surface_unsafe 2024-05-05 15:20:44 +02:00
griffi-gh 2c2199d520 ... 2024-05-05 15:19:09 +02:00
griffi-gh 1d9fafd408 lifetime errors :є 2024-05-05 13:25:54 +02:00
griffi-gh 58e4eed14e init texture prefab 2024-05-05 13:16:48 +02:00
6 changed files with 131 additions and 26 deletions

4
.gitignore vendored
View file

@ -27,3 +27,7 @@ _visualizer.json
*.so *.so
*.dylib *.dylib
*.rlib *.rlib
#but keep the dxcompiler.dll/dxil.dll
!dxcompiler.dll
!dxil.dll

View file

@ -36,8 +36,10 @@ impl AssetPaths for BlockTexture {
} }
#[derive(Unique)] #[derive(Unique)]
#[repr(transparent)] pub struct TexturePrefabs {
pub struct BlockDiffuseTexture(pub wgpu::Texture); pub block_diffuse_texture: wgpu::Texture,
pub block_diffuse_bind_group: wgpu::BindGroup,
}
#[derive(Unique)] #[derive(Unique)]
#[repr(transparent)] #[repr(transparent)]
@ -50,13 +52,63 @@ pub fn load_prefabs(
assman: UniqueView<AssetManager> assman: UniqueView<AssetManager>
) { ) {
log::info!("Loading textures..."); log::info!("Loading textures...");
storages.add_unique_non_send_sync(BlockDiffuseTexture( let block_diffuse_texture = load_texture2darray_prefab::<BlockTexture>(
load_texture2darray_prefab::<BlockTexture>(
&renderer, &renderer,
&assman, &assman,
"blocks".into(), "blocks".into(),
) );
));
log::info!("Creating bing groups");
let block_diffuse_view = block_diffuse_texture.create_view(&wgpu::TextureViewDescriptor::default());
let block_diffuse_sampler = renderer.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::Nearest,
min_filter: wgpu::FilterMode::Nearest, //TODO min_filter Linear, requires filtering sampler
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
let block_diffuse_bind_group_layout = renderer.device()
.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("block_diffuse_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
count: None,
}
]
});
let block_diffuse_bind_group = renderer.device().create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("block_diffuse_bind_group"),
layout: &block_diffuse_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&block_diffuse_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&block_diffuse_sampler),
}
]
});
storages.add_unique_non_send_sync(TexturePrefabs {
block_diffuse_texture,
block_diffuse_bind_group,
});
log::info!("Loading the UI stuff..."); log::info!("Loading the UI stuff...");
{ {

View file

@ -14,12 +14,20 @@ pub mod sumberge;
pub struct BufferPair { pub struct BufferPair {
pub index: wgpu::Buffer, pub index: wgpu::Buffer,
pub index_len: u32,
pub vertex: wgpu::Buffer, pub vertex: wgpu::Buffer,
pub vertex_len: u32,
} }
#[derive(Unique)] #[derive(Unique)]
pub struct BackgroundColor(pub Vec3); pub struct BackgroundColor(pub Vec3);
pub struct RenderCtx<'a> {
pub renderer: &'a Renderer,
pub encoder: &'a mut wgpu::CommandEncoder,
pub surface_view: &'a wgpu::TextureView,
}
pub fn render_master(storages: AllStoragesViewMut) { pub fn render_master(storages: AllStoragesViewMut) {
let renderer = storages.borrow::<UniqueView<Renderer>>().unwrap(); let renderer = storages.borrow::<UniqueView<Renderer>>().unwrap();
@ -29,11 +37,10 @@ pub fn render_master(storages: AllStoragesViewMut) {
let surface_texture = renderer.surface().get_current_texture().unwrap(); let surface_texture = renderer.surface().get_current_texture().unwrap();
let surface_view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor::default()); let surface_view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
//Main in-game render pass {
if storages.run(is_ingame) {
let bg = storages.borrow::<UniqueView<BackgroundColor>>().unwrap().0; let bg = storages.borrow::<UniqueView<BackgroundColor>>().unwrap().0;
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let _render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("main0_pass"), label: Some("rpass_background"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment { color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &surface_view, view: &surface_view,
resolve_target: None, resolve_target: None,
@ -50,10 +57,16 @@ pub fn render_master(storages: AllStoragesViewMut) {
depth_stencil_attachment: None, depth_stencil_attachment: None,
..Default::default() ..Default::default()
}); });
}
let data = (&mut render_pass, &*renderer); let mut data = RenderCtx {
renderer: &renderer,
encoder: &mut encoder,
surface_view: &surface_view,
};
storages.run_with_data(world::draw_world, data); if storages.run(is_ingame) {
storages.run_with_data(world::draw_world, &mut data);
} }
renderer.queue().submit(std::iter::once(encoder.finish())); renderer.queue().submit(std::iter::once(encoder.finish()));

View file

@ -1,3 +1,4 @@
use std::sync::Arc;
use pollster::FutureExt; use pollster::FutureExt;
use shipyard::Unique; use shipyard::Unique;
use winit::{ use winit::{
@ -9,6 +10,7 @@ use crate::settings::{GameSettings, FullscreenMode};
#[derive(Unique)] #[derive(Unique)]
pub struct Renderer { pub struct Renderer {
window: Arc<Window>,
instance: wgpu::Instance, instance: wgpu::Instance,
surface: wgpu::Surface<'static>, surface: wgpu::Surface<'static>,
device: wgpu::Device, device: wgpu::Device,
@ -16,9 +18,6 @@ pub struct Renderer {
surface_config: wgpu::SurfaceConfiguration, surface_config: wgpu::SurfaceConfiguration,
size: PhysicalSize<u32>, size: PhysicalSize<u32>,
// pub depth_texture: wgpu::Texture, // pub depth_texture: wgpu::Texture,
//must be last due to drop order
window: Window,
} }
impl Renderer { impl Renderer {
@ -71,21 +70,30 @@ impl Renderer {
None None
} }
}); });
let window = event_loop.create_window(window_attributes).unwrap(); let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
let size = window.inner_size(); let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::VULKAN | wgpu::Backends::GL, backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::VULKAN | wgpu::Backends::GL,
//Disable validation layer
flags: wgpu::InstanceFlags::default() & !wgpu::InstanceFlags::VALIDATION,
//we're using vulkan on windows
// #[cfg(all(target_os = "windows", target_arch = "x86_64"))]
// dx12_shader_compiler: wgpu::Dx12Compiler::Dxc {
// dxil_path: Some("./dxil.dll".into()),
// dxc_path: Some("./dxcompiler.dll".into()),
// },
..Default::default() ..Default::default()
}); });
// Create a surface with `create_surface_unsafe` to get a surface with 'static lifetime // Create a surface with `create_surface_unsafe` to get a surface with 'static lifetime
// It should never outlive the window it's created from // It should never outlive the window it's created from
let surface = unsafe { // let surface = unsafe {
let target = wgpu::SurfaceTargetUnsafe::from_window(&window).unwrap(); // let target = wgpu::SurfaceTargetUnsafe::from_window(&window).unwrap();
instance.create_surface_unsafe(target).unwrap() // instance.create_surface_unsafe(target).unwrap()
}; // };
let surface = instance.create_surface(Arc::clone(&window)).unwrap();
let adapter = instance.request_adapter( let adapter = instance.request_adapter(
&wgpu::RequestAdapterOptions { &wgpu::RequestAdapterOptions {

View file

@ -2,8 +2,14 @@ use bytemuck::{Pod, Zeroable};
use glam::{IVec3, Vec3}; use glam::{IVec3, Vec3};
use shipyard::{AllStoragesView, IntoIter, NonSendSync, Unique, UniqueView, UniqueViewMut, View}; use shipyard::{AllStoragesView, IntoIter, NonSendSync, Unique, UniqueView, UniqueViewMut, View};
use kubi_shared::{chunk::CHUNK_SIZE, transform::Transform}; use kubi_shared::{chunk::CHUNK_SIZE, transform::Transform};
use crate::{camera::Camera, settings::GameSettings, world::{ChunkMeshStorage, ChunkStorage}}; use wgpu::util::RenderEncoder;
use super::Renderer; use crate::{
camera::Camera,
prefabs::TexturePrefabs,
settings::GameSettings,
world::{ChunkMeshStorage, ChunkStorage},
};
use super::{RenderCtx, Renderer};
#[derive(Clone, Copy, Pod, Zeroable)] #[derive(Clone, Copy, Pod, Zeroable)]
#[repr(C, packed)] #[repr(C, packed)]
@ -35,7 +41,8 @@ pub fn init_trans_chunk_queue(storages: AllStoragesView) {
} }
pub fn draw_world( pub fn draw_world(
(render_pass, renderer): (&mut wgpu::RenderPass, &Renderer), ctx: &mut RenderCtx,
textures: UniqueView<TexturePrefabs>,
chunks: UniqueView<ChunkStorage>, chunks: UniqueView<ChunkStorage>,
meshes: NonSendSync<UniqueView<ChunkMeshStorage>>, meshes: NonSendSync<UniqueView<ChunkMeshStorage>>,
transform: View<Transform>, transform: View<Transform>,
@ -46,6 +53,19 @@ pub fn draw_world(
let camera = camera.iter().next().expect("No cameras in the scene"); let camera = camera.iter().next().expect("No cameras in the scene");
let camera_matrix = camera.view_matrix * camera.perspective_matrix; let camera_matrix = camera.view_matrix * camera.perspective_matrix;
let mut render_pass = ctx.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("draw_world"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: ctx.surface_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
for (&position, chunk) in &chunks.chunks { for (&position, chunk) in &chunks.chunks {
if let Some(key) = chunk.mesh_index { if let Some(key) = chunk.mesh_index {
let mesh = meshes.get(key).expect("Mesh index pointing to nothing"); let mesh = meshes.get(key).expect("Mesh index pointing to nothing");
@ -66,6 +86,10 @@ pub fn draw_world(
//Draw chunk mesh //Draw chunk mesh
if mesh.main.index.size() > 0 { if mesh.main.index.size() > 0 {
//TODO //TODO
render_pass.set_index_buffer(mesh.main.index.slice(..), wgpu::IndexFormat::Uint32);
render_pass.set_vertex_buffer(0, mesh.main.vertex.slice(..));
render_pass.set_bind_group(0, &textures.block_diffuse_bind_group, &[]);
render_pass.draw_indexed(0..mesh.main.index_len, 0, 0..1);
} }
//TODO trans chunks //TODO trans chunks

View file

@ -355,12 +355,16 @@ fn process_completed_tasks(
let main_buffer_pair = BufferPair { let main_buffer_pair = BufferPair {
vertex: vtx_buffer, vertex: vtx_buffer,
vertex_len: vertices.len() as u32,
index: idx_buffer, index: idx_buffer,
index_len: indices.len() as u32,
}; };
let trans_buffer_pair = BufferPair { let trans_buffer_pair = BufferPair {
vertex: vtx_buffer_trans, vertex: vtx_buffer_trans,
vertex_len: vertices.len() as u32,
index: idx_buffer_trans, index: idx_buffer_trans,
index_len: indices.len() as u32,
}; };
let mesh = ChunkMesh { let mesh = ChunkMesh {