Compare commits

..

3 Commits

@ -1,5 +1,5 @@
[package]
name = "tri"
name = "particles"
version = "0.1.0"
edition = "2021"

@ -1,131 +0,0 @@
let SessionLoad = 1
let s:so_save = &g:so | let s:siso_save = &g:siso | setg so=0 siso=0 | setl so=-1 siso=-1
let v:this_session=expand("<sfile>:p")
silent only
silent tabonly
cd ~/bin/rs/tri
if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''
let s:wipebuf = bufnr('%')
endif
let s:shortmess_save = &shortmess
if &shortmess =~ 'A'
set shortmess=aoOA
else
set shortmess=aoO
endif
badd +1 ~/bin/rs/tri
badd +1 src/render.rs
badd +0 src/utility/share.rs
argglobal
%argdel
$argadd ~/bin/rs/tri
edit src/render.rs
let s:save_splitbelow = &splitbelow
let s:save_splitright = &splitright
set splitbelow splitright
wincmd _ | wincmd |
vsplit
wincmd _ | wincmd |
vsplit
2wincmd h
wincmd w
wincmd w
let &splitbelow = s:save_splitbelow
let &splitright = s:save_splitright
wincmd t
let s:save_winminheight = &winminheight
let s:save_winminwidth = &winminwidth
set winminheight=0
set winheight=1
set winminwidth=0
set winwidth=1
exe 'vert 1resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 2resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 3resize ' . ((&columns * 70 + 107) / 214)
argglobal
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 61 - ((45 * winheight(0) + 40) / 81)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 61
normal! 0
lcd ~/bin/rs/tri
wincmd w
argglobal
if bufexists(fnamemodify("~/bin/rs/tri/src/utility/share.rs", ":p")) | buffer ~/bin/rs/tri/src/utility/share.rs | else | edit ~/bin/rs/tri/src/utility/share.rs | endif
if &buftype ==# 'terminal'
silent file ~/bin/rs/tri/src/utility/share.rs
endif
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 190 - ((53 * winheight(0) + 40) / 81)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 190
normal! 013|
lcd ~/bin/rs/tri
wincmd w
argglobal
if bufexists(fnamemodify("~/bin/rs/tri/src/utility/share.rs", ":p")) | buffer ~/bin/rs/tri/src/utility/share.rs | else | edit ~/bin/rs/tri/src/utility/share.rs | endif
if &buftype ==# 'terminal'
silent file ~/bin/rs/tri/src/utility/share.rs
endif
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 1651 - ((36 * winheight(0) + 40) / 81)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 1651
normal! 016|
lcd ~/bin/rs/tri
wincmd w
3wincmd w
exe 'vert 1resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 2resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 3resize ' . ((&columns * 70 + 107) / 214)
tabnext 1
if exists('s:wipebuf') && len(win_findbuf(s:wipebuf)) == 0 && getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'
silent exe 'bwipe ' . s:wipebuf
endif
unlet! s:wipebuf
set winheight=1 winwidth=20
let &shortmess = s:shortmess_save
let &winminheight = s:save_winminheight
let &winminwidth = s:save_winminwidth
let s:sx = expand("<sfile>:p:r")."x.vim"
if filereadable(s:sx)
exe "source " . fnameescape(s:sx)
endif
let &g:so = s:so_save | let &g:siso = s:siso_save
set hlsearch
doautoall SessionLoadPost
unlet SessionLoad
" vim: set ft=vim :

@ -6,6 +6,11 @@ use std::process::Command;
fn main() -> std::io::Result<()> {
println!("building shaders...");
//rm shader target path if it exists
if Path::new("./target/shaders").exists() {
println!("exists");
Command::new("rm").args(["-rf", "target/shaders"]).status().unwrap();
}
//shaders path
let shaders = Path::new("./src/shaders");
//shader target path

@ -0,0 +1,90 @@
[Debug][Warning][General]"vkCreateInstance: The API Variant specified in pCreateInfo->pApplicationInfo.apiVersion is 1 instead of the expected value of 0."
[Debug][Warning][General]"Override layer has override paths set to /usr/share/vulkan/explicit_layer.d"
[Debug][Warning][General]"Layer VK_LAYER_KHRONOS_validation uses API version 1.3 which is older than the application specified API version of 3.251. May cause issues."
WARNING-CreateInstance-status-message(INFO / SPEC): msgNum: 601872502 - Validation Information: [ WARNING-CreateInstance-status-message ] Object 0: handle = 0x593d84af09c0, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x23dfd876 | vkCreateInstance(): Khronos Validation Layer Active:
Settings File: Found at /root/.local/share/vulkan/settings.d/vk_layer_settings.txt specified by VkConfig application override.
Current Enables: None.
Current Disables: None.
Objects: 1
[0] 0x593d84af09c0, type: 1, name: NULL
shader stage: FRAGMENT
shader stage: VERTEX
THETA 1.9669454
THETA 0.9690302
THETA 5.544452
THETA 1.6390675
THETA 4.45788
gen: [Particle { pos: (-0.05296515, 0.18994758), vel: (10000.1, 10000.1), color: (0.16731358, 0.7073207, 0.3619156, 1.0) }, Particle { pos: (0.08795657, 0.19211969), vel: (10000.1, 10000.1), color: (0.5379406, 0.90588605, 0.9700917, 1.0) }, Particle { pos: (0.034558054, -0.047211617), vel: (10000.1, 10000.1), color: (0.23748064, 0.27166975, 0.36598802, 1.0) }, Particle { pos: (-0.010261379, 0.22510439), vel: (10000.1, 10000.1), color: (0.36035168, 0.7322073, 0.6743896, 1.0) }, Particle { pos: (-0.029471215, -0.16992791), vel: (10000.1, 10000.1), color: (0.861714, 0.9068495, 0.2577982, 1.0) }]
particles count: 5, particle size: 32, buffer size: 160
actual buffer size: 160
memory allocation size: 160
isize max is 9223372036854775807
mapping device memory
mem req: 160
DATA INSIDE PARTICLES BUFFER: PARTICLES, LEN IS 5
Particle {
pos: (-0.05296515, 0.18994758)
vel: (10000.1, 10000.1)
color: (0.16731358, 0.7073207, 0.3619156, 1.0)
} Particle {
pos: (0.08795657, 0.19211969)
vel: (10000.1, 10000.1)
color: (0.5379406, 0.90588605, 0.9700917, 1.0)
} Particle {
pos: (0.034558054, -0.047211617)
vel: (10000.1, 10000.1)
color: (0.23748064, 0.27166975, 0.36598802, 1.0)
} Particle {
pos: (-0.010261379, 0.22510439)
vel: (10000.1, 10000.1)
color: (0.36035168, 0.7322073, 0.6743896, 1.0)
} Particle {
pos: (-0.029471215, -0.16992791)
vel: (10000.1, 10000.1)
color: (0.861714, 0.9068495, 0.2577982, 1.0)
}
actual buffer size: 160
memory allocation size: 160
src_buffer: 0x908683000000001d
dst_buffer: 0x2e2941000000001f
actual buffer size: 160
memory allocation size: 160
src_buffer: 0x908683000000001d
dst_buffer: 0xc4f3070000000021
actual buffer size: 4
memory allocation size: 4
actual buffer size: 4
memory allocation size: 4
STORAGE BUFFERS INDEXES: 1, 0
STORAGE BUFFERS INDEXES: 0, 1
resizing framebuffer event
VUID-VkQueryPoolCreateInfo-queryType-00791(ERROR / SPEC): msgNum: 619941015 - Validation Error: [ VUID-VkQueryPoolCreateInfo-queryType-00791 ] | MessageID = 0x24f38c97 | vkCreateQueryPool(): pCreateInfo->queryType is VK_QUERY_TYPE_PIPELINE_STATISTICS but pipelineStatisticsQuery feature was not enabled. The Vulkan spec states: If the pipelineStatisticsQuery feature is not enabled, queryType must not be VK_QUERY_TYPE_PIPELINE_STATISTICS (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkQueryPoolCreateInfo-queryType-00791)
Objects: 0
[Debug][Error][Validation]"Validation Error: [ VUID-VkQueryPoolCreateInfo-queryType-00791 ] | MessageID = 0x24f38c97 | vkCreateQueryPool(): pCreateInfo->queryType is VK_QUERY_TYPE_PIPELINE_STATISTICS but pipelineStatisticsQuery feature was not enabled. The Vulkan spec states: If the pipelineStatisticsQuery feature is not enabled, queryType must not be VK_QUERY_TYPE_PIPELINE_STATISTICS (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkQueryPoolCreateInfo-queryType-00791)"
VUID-vkCmdBeginQuery-commandBuffer-recording(ERROR / SPEC): msgNum: -502516869 - Validation Error: [ VUID-vkCmdBeginQuery-commandBuffer-recording ] Object 0: handle = 0x593d85ab7d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0xe20c337b | vkCmdBeginQuery(): was called before vkBeginCommandBuffer(). The Vulkan spec states: commandBuffer must be in the recording state (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdBeginQuery-commandBuffer-recording)
Objects: 1
[0] 0x593d85ab7d40, type: 6, name: NULL
[Debug][Error][Validation]"Validation Error: [ VUID-vkCmdBeginQuery-commandBuffer-recording ] Object 0: handle = 0x593d85ab7d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0xe20c337b | vkCmdBeginQuery(): was called before vkBeginCommandBuffer(). The Vulkan spec states: commandBuffer must be in the recording state (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdBeginQuery-commandBuffer-recording)"
binding to shader storage buffer index: 0
VUID-vkCmdEndQuery-None-01923(ERROR / SPEC): msgNum: -231257939 - Validation Error: [ VUID-vkCmdEndQuery-None-01923 ] Object 0: handle = 0x593d85ab7d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; Object 1: handle = 0x9638f80000000036, type = VK_OBJECT_TYPE_QUERY_POOL; | MessageID = 0xf23748ad | vkCmdEndQuery(): Ending a query before it was started: VkQueryPool 0x9638f80000000036[], index 0. The Vulkan spec states: All queries used by the command must be active (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdEndQuery-None-01923)
Objects: 2
[0] 0x593d85ab7d40, type: 6, name: NULL
[1] 0x9638f80000000036, type: 12, name: NULL
[Debug][Error][Validation]"Validation Error: [ VUID-vkCmdEndQuery-None-01923 ] Object 0: handle = 0x593d85ab7d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; Object 1: handle = 0x9638f80000000036, type = VK_OBJECT_TYPE_QUERY_POOL; | MessageID = 0xf23748ad | vkCmdEndQuery(): Ending a query before it was started: VkQueryPool 0x9638f80000000036[], index 0. The Vulkan spec states: All queries used by the command must be active (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdEndQuery-None-01923)"
VUID-vkCmdEndQuery-commandBuffer-recording(ERROR / SPEC): msgNum: 1820876487 - Validation Error: [ VUID-vkCmdEndQuery-commandBuffer-recording ] Object 0: handle = 0x593d85ab7d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x6c885ec7 | vkCmdEndQuery(): was called before vkBeginCommandBuffer(). The Vulkan spec states: commandBuffer must be in the recording state (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdEndQuery-commandBuffer-recording)
Objects: 1
[0] 0x593d85ab7d40, type: 6, name: NULL
[Debug][Error][Validation]"Validation Error: [ VUID-vkCmdEndQuery-commandBuffer-recording ] Object 0: handle = 0x593d85ab7d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x6c885ec7 | vkCmdEndQuery(): was called before vkBeginCommandBuffer(). The Vulkan spec states: commandBuffer must be in the recording state (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdEndQuery-commandBuffer-recording)"
VUID-vkGetQueryPoolResults-flags-00815(ERROR / SPEC): msgNum: 2025983256 - Validation Error: [ VUID-vkGetQueryPoolResults-flags-00815 ] | MessageID = 0x78c20d18 | vkGetQueryPoolResults(): stride 4 or dataSize 4 is invalid. The Vulkan spec states: If VK_QUERY_RESULT_64_BIT is set in flags then pData and stride must be multiples of 8 (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkGetQueryPoolResults-flags-00815)
Objects: 0
[Debug][Error][Validation]"Validation Error: [ VUID-vkGetQueryPoolResults-flags-00815 ] | MessageID = 0x78c20d18 | vkGetQueryPoolResults(): stride 4 or dataSize 4 is invalid. The Vulkan spec states: If VK_QUERY_RESULT_64_BIT is set in flags then pData and stride must be multiples of 8 (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkGetQueryPoolResults-flags-00815)"
VUID-vkGetQueryPoolResults-dataSize-00817(ERROR / SPEC): msgNum: 1933008596 - Validation Error: [ VUID-vkGetQueryPoolResults-dataSize-00817 ] Object 0: handle = 0x9638f80000000036, type = VK_OBJECT_TYPE_QUERY_POOL; | MessageID = 0x73375ed4 | vkGetQueryPoolResults(): queryPool (VkQueryPool 0x9638f80000000036[]) specified dataSize 4 which is incompatible with the specified query type and options. The Vulkan spec states: dataSize must be large enough to contain the result of each query, as described here (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkGetQueryPoolResults-dataSize-00817)
Objects: 1
[0] 0x9638f80000000036, type: 12, name: NULL
[Debug][Error][Validation]"Validation Error: [ VUID-vkGetQueryPoolResults-dataSize-00817 ] Object 0: handle = 0x9638f80000000036, type = VK_OBJECT_TYPE_QUERY_POOL; | MessageID = 0x73375ed4 | vkGetQueryPoolResults(): queryPool (VkQueryPool 0x9638f80000000036[]) specified dataSize 4 which is incompatible with the specified query type and options. The Vulkan spec states: dataSize must be large enough to contain the result of each query, as described here (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkGetQueryPoolResults-dataSize-00817)"
VUID-vkGetQueryPoolResults-None-09401(ERROR / SPEC): msgNum: 1316435884 - Validation Error: [ VUID-vkGetQueryPoolResults-None-09401 ] Object 0: handle = 0x9638f80000000036, type = VK_OBJECT_TYPE_QUERY_POOL; | MessageID = 0x4e7737ac | vkGetQueryPoolResults(): queryPool VkQueryPool 0x9638f80000000036[] and query 0: query not reset. After query pool creation, each query must be reset before it is used. Queries must also be reset between uses. The Vulkan spec states: All queries used by the command must not be uninitialized (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkGetQueryPoolResults-None-09401)
Objects: 1
[0] 0x9638f80000000036, type: 12, name: NULL
[Debug][Error][Validation]"Validation Error: [ VUID-vkGetQueryPoolResults-None-09401 ] Object 0: handle = 0x9638f80000000036, type = VK_OBJECT_TYPE_QUERY_POOL; | MessageID = 0x4e7737ac | vkGetQueryPoolResults(): queryPool VkQueryPool 0x9638f80000000036[] and query 0: query not reset. After query pool creation, each query must be reset before it is used. Queries must also be reset between uses. The Vulkan spec states: All queries used by the command must not be uninitialized (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkGetQueryPoolResults-None-09401)"

2508
rnd.rs

File diff suppressed because it is too large Load Diff

@ -8,15 +8,51 @@ use rand::{
use crate::utility::constants::*;
use std::f32::consts::PI;
use std::ffi::c_void;
use std::{ fmt, slice };
pub const PARTICLE_COUNT: u64 = 1;
pub const PARTICLE_COUNT: u64 = 5;
#[repr(C)]
#[derive(Clone, Debug, Copy)]
pub struct Particle {
pos: (f32, f32),
vel: (f32, f32),
color: (f32, f32, f32, f32),
pub pos: (f32, f32),
pub vel: (f32, f32),
pub color: (f32, f32, f32, f32),
}
pub struct ParticlesList(pub Vec<Particle>);
impl ParticlesList {
pub fn from_vec(particles: Vec<Particle>) -> ParticlesList {
ParticlesList(particles)
}
pub fn from_raw_ptr(ptr: *const Particle, len: usize) -> ParticlesList {
let mut vec = vec![];
vec.extend_from_slice(
unsafe { slice::from_raw_parts(ptr, len) as &[Particle] }
);
ParticlesList(
vec
)
}
}
impl fmt::Display for ParticlesList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PARTICLES, LEN IS {}\n\n", self.0.len())?;
for (i, particle) in self.0.iter().enumerate() {
write!(
f,
" Particle {{\n pos: {:?}\n vel: {:?}\n color: {:?}\n }}",
particle.pos,
particle.vel,
particle.color,
)?;
}
Ok(())
}
}
fn normalize(vec2: (f32, f32)) -> (f32, f32) {
@ -46,10 +82,11 @@ impl Particle {
println!("THETA {}", theta);
let x = r * theta.cos() * WINDOW_HEIGHT as f32 / WINDOW_WIDTH as f32;
let y = r * theta.sin();
let (x, y) = (10.0, 0.0);
//let (x, y) = (100000.0, 0.0);
res.push(Particle {
pos: (x, y),
vel: vec2_scalar_mul(normalize((x, y)), 0.00025),
//vel: vec2_scalar_mul(normalize((x, y)), 0.00025),
vel: (10000.1, 10000.1),
color: (
between.sample(&mut rng),
between.sample(&mut rng),

@ -5,15 +5,14 @@ pub mod render;
pub mod shaders;
pub mod utility;
use render::{ App, ProgramProc };
use render::{ App };
use utility::window::*;
use winit::event_loop::EventLoop;
fn main() {
let program = ProgramProc {
event_loop: EventLoop::new()
};
let program = ProgramProc::new();
let app = App::new();
let app = App::new(&program.event_loop);
program.main_loop(app);
}
// -------------------------------------------------------------------------------------------

@ -2,6 +2,7 @@ use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEve
use winit::event_loop::{ControlFlow, EventLoop};
use ash::vk;
use ash::util::Align;
use image;
use image::GenericImageView;
@ -13,11 +14,13 @@ use crate::utility::fps_limiter::*;
use crate::utility::{debug, platforms};
use crate::utility::tools::*;
use crate::entities::*;
use crate::VulkanApp;
use crate::shaders::shaders;
use std::ffi::CString;
use std::ptr;
use std::mem::size_of;
use std::mem;
use mem::size_of;
use std::default;
use std::os::raw::{ c_void, c_char };
@ -27,76 +30,6 @@ const WINDOW_TITLE: &'static str = "Template";
const IS_PAINT_FPS_COUNTER: bool = true;
pub struct ProgramProc {
pub event_loop: EventLoop<()>,
}
impl ProgramProc {
pub fn new() -> ProgramProc {
// init window stuff
let event_loop = EventLoop::new();
ProgramProc { event_loop }
}
pub fn main_loop(self, mut vulkan_app: App) {
let mut tick_counter = utility::fps_limiter::FPSLimiter::new();
self.event_loop.run(move |event, _, control_flow| {
match event {
| Event::WindowEvent { event, .. } => {
match event {
| WindowEvent::CloseRequested => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
},
| WindowEvent::KeyboardInput { input, .. } => {
match input {
| KeyboardInput { virtual_keycode, state, .. } => {
match (virtual_keycode, state) {
| (Some(VirtualKeyCode::Escape), ElementState::Pressed) => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
},
| _ => {},
}
},
}
},
| WindowEvent::Resized(_new_size) => {
vulkan_app.wait_device_idle();
vulkan_app.is_framebuffer_resized = true;
},
| _ => {},
}
},
| Event::MainEventsCleared => {
&vulkan_app.window.request_redraw();
},
| Event::RedrawRequested(_window_id) => {
let delta_time = tick_counter.delta_time();
vulkan_app.draw_frame();
if IS_PAINT_FPS_COUNTER {
print!("FPS: {}\r", tick_counter.fps());
}
tick_counter.tick_frame();
},
| Event::LoopDestroyed => {
vulkan_app.wait_device_idle();
},
_ => (),
}
})
}
}
pub fn create_instance(
entry: &ash::Entry,
window_title: &str,
@ -240,9 +173,8 @@ pub fn find_memory_type(
panic!("Failed to find suitable memory type!")
}
pub struct App {
pub struct App<'a> {
pub window: winit::window::Window,
pub event_loop: winit::event_loop::EventLoop<()>,
// vulkan stuff
pub entry: ash::Entry,
@ -313,12 +245,15 @@ pub struct App {
pub last_time: f64,
pub physical_device_memory_properties: vk::PhysicalDeviceMemoryProperties,
pub query_pool: vk::QueryPool,
pub query_memory: vk::DeviceMemory,
pub query_mapped: &'a mut [u64],
}
impl App {
impl<'a> App<'a> {
pub fn new() -> Self {
let event_loop = winit::event_loop::EventLoop::new();
pub fn new(event_loop: &winit::event_loop::EventLoop<()>) -> Self {
let window = init_window(&event_loop, WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT);
let entry = unsafe { ash::Entry::load().unwrap() };
@ -393,14 +328,91 @@ impl App {
let command_buffers = Self::create_command_buffers(&device, command_pool);
let compute_command_buffers = Self::create_command_buffers(&device, command_pool);
let compute_command_buffers = Self::create_compute_command_buffers(&device, command_pool);
let sync_objects = SyncObjects::new(&device, MAX_FRAMES_IN_FLIGHT);
//setup logging of compute shader invocations
// Define the buffer to hold query results
let mut query_results_data: [u64; 1] = [0]; // Assuming we're querying one result
// Create a buffer to hold the query results
let buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
size: 8,
usage: vk::BufferUsageFlags::TRANSFER_DST,
sharing_mode: vk::SharingMode::EXCLUSIVE,
..Default::default()
};
let query_result_buffer = unsafe {
device
.create_buffer(&buffer_info, None)
.expect("Failed to create query result buffer")
};
// Allocate memory for the buffer
let mem_requirements = unsafe { device.get_buffer_memory_requirements(query_result_buffer) };
let memory_type_index = find_memory_type(
mem_requirements.memory_type_bits,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
&physical_device_memory_properties,
);
let allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
allocation_size: mem_requirements.size,
memory_type_index,
..Default::default()
};
let query_memory = unsafe {
device
.allocate_memory(&allocate_info, None)
.expect("Failed to allocate query result memory")
};
unsafe {
// Bind the buffer with allocated memory
device
.bind_buffer_memory(query_result_buffer, query_memory, 0)
.expect("Failed to bind buffer memory")
};
// Now we can use this buffer to store query results
let query_mapped = unsafe {
let raw_ptr = device
.map_memory(
query_memory,
0,
std::mem::size_of_val(&query_results_data) as u64,
vk::MemoryMapFlags::empty(),
)
.expect("Failed to map memory");
std::slice::from_raw_parts_mut(raw_ptr as *mut u64, 1)
};
// Create a query pool
let query_pool_info = vk::QueryPoolCreateInfo {
s_type: vk::StructureType::QUERY_POOL_CREATE_INFO,
query_type: vk::QueryType::PIPELINE_STATISTICS,
query_count: 1, // We're only querying one statistic
pipeline_statistics: vk::QueryPipelineStatisticFlags::COMPUTE_SHADER_INVOCATIONS,
..Default::default()
};
let query_pool = unsafe {
device
.create_query_pool(&query_pool_info, None)
.expect("Failed to create query pool")
};
Self {
window,
event_loop,
entry,
instance,
@ -451,79 +463,14 @@ impl App {
last_time: 0.0,
physical_device_memory_properties,
}
}
/*fn create_vertex_buffer(
instance: &ash::Instance,
device: &ash::Device,
physical_device: vk::PhysicalDevice,
) -> (vk::Buffer, vk::DeviceMemory) {
let vertex_buffer_create_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: std::mem::size_of_val(&TRI_VERT_DATA) as u64,
usage: vk::BufferUsageFlags::VERTEX_BUFFER
| vk::BufferUsageFlags::STORAGE_BUFFER
| vk::BufferUsageFlags::TRANSFER_DST,
sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0,
p_queue_family_indices: ptr::null(),
};
let vertex_buffer = unsafe {
device
.create_buffer(&vertex_buffer_create_info, None)
.expect("Failed to create Vertex Buffer")
};
let mem_requirements = unsafe { device.get_buffer_memory_requirements(vertex_buffer) };
let mem_properties =
unsafe { instance.get_physical_device_memory_properties(physical_device) };
let required_memory_flags: vk::MemoryPropertyFlags =
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
let memory_type = App::find_memory_type(
mem_requirements.memory_type_bits,
required_memory_flags,
mem_properties,
);
let allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: mem_requirements.size,
memory_type_index: memory_type,
};
let vertex_buffer_memory = unsafe {
device
.allocate_memory(&allocate_info, None)
.expect("Failed to allocate vertex buffer memory!")
};
unsafe {
device
.bind_buffer_memory(vertex_buffer, vertex_buffer_memory, 0)
.expect("Failed to bind Buffer");
let data_ptr = device
.map_memory(
vertex_buffer_memory,
0,
vertex_buffer_create_info.size,
vk::MemoryMapFlags::empty(),
)
.expect("Failed to Map Memory") as *mut Vertex;
query_pool,
query_memory,
query_mapped,
data_ptr.copy_from_nonoverlapping(TRI_VERT_DATA.as_ptr(), TRI_VERT_DATA.len());
device.unmap_memory(vertex_buffer_memory);
}
(vertex_buffer, vertex_buffer_memory)
}*/
}
fn find_memory_type(
type_filter: u32,
@ -549,6 +496,7 @@ impl App {
for (shader, stage_i) in shaders() {
//check if graphics shader
if stage_i == vk::ShaderStageFlags::VERTEX || stage_i == vk::ShaderStageFlags::FRAGMENT {
println!("shader stage: {:?}", stage_i);
shader_modules.push(
vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
@ -812,25 +760,35 @@ impl App {
fn record_compute_command_buffer(
&self,
device: &ash::Device,
&mut self,
command_buffer: vk::CommandBuffer
) {
let begin_info = vk::CommandBufferBeginInfo::default();
unsafe {
device
self.device
.begin_command_buffer(command_buffer, &begin_info)
.expect("failed to begin recording compute command buffer");
device
println!("resetting query pool for command buffer: {}", self.current_frame);
self.device
.cmd_reset_query_pool(
self.compute_command_buffers[self.current_frame],
self.query_pool,
0,
1,
);
self.device.cmd_begin_query(self.compute_command_buffers[self.current_frame], self.query_pool, 0, vk::QueryControlFlags::empty());
self.device
.cmd_bind_pipeline(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
self.compute_pipeline,
);
device
self.device
.cmd_bind_descriptor_sets(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
@ -840,169 +798,36 @@ impl App {
&[],
);
device
self.device
.cmd_dispatch(
command_buffer,
(PARTICLE_COUNT / 256) as u32,
1,
1,
);
device
.end_command_buffer(command_buffer)
.expect("failed ending compute command buffer");
}
}
fn draw_frame(&mut self) {
//compute submission
let mut submit_infos;
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.compute_inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
self.update_uniform_buffer(self.current_frame);
unsafe {
self.device
.reset_fences(&[self.sync_objects.compute_inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(self.compute_command_buffers[self.current_frame], vk::CommandBufferResetFlags::empty());
}
self.record_compute_command_buffer(&self.device, self.compute_command_buffers[self.current_frame]);
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.compute_command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.compute_finished_semaphores[self.current_frame],
..Default::default()
}];
unsafe {
self.device
.queue_submit(
self.compute_queue,
&submit_infos,
self.sync_objects.compute_inflight_fences[self.current_frame]
);
}
//graphics submission
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
let (image_index, _is_sub_optimal) = unsafe {
let result = self.swapchain_stuff.swapchain_loader.acquire_next_image(
self.swapchain_stuff.swapchain,
std::u64::MAX,
self.sync_objects.image_available_semaphores[self.current_frame],
vk::Fence::null(),
);
match result {
Ok(image_index) => image_index,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR => {
SwapChainStuff::recreate_swapchain(self);
return;
}
_ => panic!("Failed to acquire Swap Chain Image!"),
},
}
};
unsafe {
self.device
.reset_fences(&[self.sync_objects.inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(
self.command_buffers[self.current_frame],
vk::CommandBufferResetFlags::empty(),
);
}
self.record_command_buffer(self.command_buffers[self.current_frame], image_index as usize);
let wait_semaphores = [
self.sync_objects.compute_finished_semaphores[self.current_frame],
self.sync_objects.image_available_semaphores[self.current_frame],
];
let wait_stages = [
vk::PipelineStageFlags::VERTEX_INPUT,
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
];
//log compute shader invocations
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
wait_semaphore_count: 2,
p_wait_semaphores: wait_semaphores.as_ptr(),
p_wait_dst_stage_mask: wait_stages.as_ptr(),
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
..Default::default()
}];
self.device.cmd_end_query(self.compute_command_buffers[self.current_frame], self.query_pool, 0);
unsafe {
self.device
.queue_submit(
self.graphics_queue,
&submit_infos,
self.sync_objects.inflight_fences[self.current_frame],
/*let query_results = unsafe {
self.device.get_query_pool_results::<u64>(
self.query_pool,
0, // Starting query index
1, // Number of queries to retrieve (1 in this case)
self.query_mapped, // Results will be stored here
//0, // Query results stride (optional)
vk::QueryResultFlags::TYPE_64, // Flags specifying the type of query results
)
.expect("failed to submit draw command buffer");
}
.expect("Failed to retrieve query pool results"
)};
let swapchains = [self.swapchain_stuff.swapchain];
println!("Compute shader invocations: {:?}", self.query_mapped[0]);*/
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PRESENT_INFO_KHR,
p_next: ptr::null(),
wait_semaphore_count: 1,
p_wait_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
swapchain_count: 1,
p_swapchains: swapchains.as_ptr(),
p_image_indices: &image_index,
p_results: ptr::null_mut(),
};
let result = unsafe {
self.swapchain_stuff.swapchain_loader
.queue_present(self.present_queue, &present_info)
};
let is_resized = match result {
Ok(_) => self.is_framebuffer_resized,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR | vk::Result::SUBOPTIMAL_KHR => true,
_ => panic!("Failed to execute queue present."),
},
};
if is_resized {
self.is_framebuffer_resized = false;
SwapChainStuff::recreate_swapchain(self);
self.device
.end_command_buffer(command_buffer)
.expect("failed ending compute command buffer");
}
self.current_frame = (self.current_frame + 1) % MAX_FRAMES_IN_FLIGHT;
}
pub fn create_shader_storage_buffers(
@ -1013,7 +838,13 @@ impl App {
) -> (Vec<vk::Buffer>, Vec<vk::DeviceMemory>) {
let mut particles = Particle::gen();
let buffer_size: u64 = std::mem::size_of::<Particle>() as u64 * PARTICLE_COUNT as u64;
let mut particles_slice_data = particles.as_mut_slice();
//let mut slice = Align::new();
let mut buffer_size: u64 = std::mem::size_of::<Particle>() as u64 * particles_slice_data.len() as u64;
println!("particles count: {}, particle size: {}, buffer size: {}", PARTICLE_COUNT as u64, std::mem::size_of::<Particle>() as u64, buffer_size as usize);
let (staging_buffer, staging_buffer_memory) = Self::create_buffer(
@ -1029,7 +860,9 @@ impl App {
let mut shader_storage_buffers_memory = vec![];
unsafe {
let data = device
println!("isize max is {}", isize::MAX);
println!("mapping device memory");
let mut data = device
.map_memory(
staging_buffer_memory,
0,
@ -1037,11 +870,21 @@ impl App {
vk::MemoryMapFlags::empty(),
)
.expect("failed to map shader storage buffer memory");
ptr::copy_nonoverlapping(
let mem_requirements = unsafe { device.get_buffer_memory_requirements(staging_buffer) };
println!("mem req: {}", mem_requirements.size);
let mut slice = Align::new(
data,
particles.as_mut_ptr() as *mut c_void,
buffer_size as usize,
mem::align_of::<Particle>() as u64,
mem_requirements.size,
);
slice.copy_from_slice(&particles_slice_data);
println!("DATA INSIDE PARTICLES BUFFER: {}", ParticlesList::from_raw_ptr(data as *const Particle, particles.len()));
//println!("copying to device memory");
device
.unmap_memory(staging_buffer_memory);
@ -1052,7 +895,8 @@ impl App {
vk::BufferUsageFlags::STORAGE_BUFFER |
vk::BufferUsageFlags::VERTEX_BUFFER |
vk::BufferUsageFlags::TRANSFER_DST,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
vk::MemoryPropertyFlags::DEVICE_LOCAL |
vk::MemoryPropertyFlags::HOST_VISIBLE,
physical_device_memory_properties,
);
@ -1134,6 +978,9 @@ impl App {
device.end_command_buffer(alloced_command_buffer);
}
println!("src_buffer: {:?}", src_buffer);
println!("dst_buffer: {:?}", dst_buffer);
let submit_info = vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
command_buffer_count: 1,
@ -1177,6 +1024,7 @@ impl App {
p_queue_family_indices: ptr::null(),
};
println!("actual buffer size: {}", size);
let buffer = unsafe {
device
.create_buffer(&buffer_create_info, None)
@ -1185,6 +1033,8 @@ impl App {
let mem_requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
println!("memory allocation size: {}", mem_requirements.size);
let allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
@ -1278,6 +1128,7 @@ impl App {
let physical_device_features = vk::PhysicalDeviceFeatures {
sampler_anisotropy: vk::TRUE, // enable anisotropy device feature from Chapter-24.
pipeline_statistics_query: vk::TRUE,
..Default::default()
};
@ -1349,7 +1200,7 @@ impl App {
}
let clear_color = [vk::ClearValue {
color: vk::ClearColorValue {
float32: [1.0, 1.0, 1.0, 1.0],
float32: [0.0, 0.0, 1.0, 1.0],
},
}];
@ -1424,6 +1275,7 @@ impl App {
&[self.shader_storage_buffers[self.current_frame]],
offsets,
);
println!("binding to shader storage buffer index: {}", self.current_frame);
self.device
.cmd_draw(
command_buffer,
@ -1851,6 +1703,8 @@ impl App {
range: size_of::<UniformBufferObject>() as u64,
};
println!("STORAGE BUFFERS INDEXES: {}, {}", (i as i32 - 1) as usize % MAX_FRAMES_IN_FLIGHT, i);
let storage_buffer_info_last_frame = vk::DescriptorBufferInfo {
buffer: shader_storage_buffers[(i as i32 - 1) as usize % MAX_FRAMES_IN_FLIGHT],
offset: 0,
@ -1978,6 +1832,27 @@ impl App {
command_buffers
}
pub fn create_compute_command_buffers(
device: &ash::Device,
command_pool: vk::CommandPool,
) -> Vec<vk::CommandBuffer> {
let command_buffer_allocate_info = vk::CommandBufferAllocateInfo {
s_type: vk::StructureType::COMMAND_BUFFER_ALLOCATE_INFO,
p_next: ptr::null(),
command_buffer_count: MAX_FRAMES_IN_FLIGHT as u32,
command_pool,
level: vk::CommandBufferLevel::PRIMARY,
};
let command_buffers = unsafe {
device
.allocate_command_buffers(&command_buffer_allocate_info)
.expect("Failed to allocate Command Buffers!")
};
command_buffers
}
fn wait_device_idle(&self) {
unsafe {
self.device
@ -1986,3 +1861,238 @@ impl App {
};
}
}
impl VulkanApp for App<'_> {
fn wait_device_idle(&self) {
unsafe {
self.device
.device_wait_idle()
.expect("Failed to wait device idle!")
};
}
fn resize_framebuffer(&mut self) {
self.is_framebuffer_resized = true;
}
fn window_ref(&self) -> &winit::window::Window {
&self.window
}
fn cleanup_swapchain(&self) {
self.swapchain_stuff.cleanup_swapchain(&self.device)
}
fn recreate_swapchain(&mut self) {
SwapChainStuff::recreate_swapchain(self);
}
fn draw_frame(&mut self) {
let mut buffer_size: u64 = std::mem::size_of::<Particle>() as u64 * PARTICLE_COUNT as u64;
//compute submission
let mut submit_infos;
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.compute_inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
self.update_uniform_buffer(self.current_frame);
unsafe {
self.device
.reset_fences(&[self.sync_objects.compute_inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(self.compute_command_buffers[self.current_frame], vk::CommandBufferResetFlags::empty());
}
//RESET query pool for compute shader statistics
/*unsafe {
self.device
.cmd_reset_query_pool(
self.compute_command_buffers[self.current_frame],
self.query_pool,
0,
1,
);
}*/
self.record_compute_command_buffer(self.compute_command_buffers[self.current_frame]);
self.update_uniform_buffer(self.current_frame);
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.compute_command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.compute_finished_semaphores[self.current_frame],
..Default::default()
}];
unsafe {
self.device
.queue_submit(
self.compute_queue,
&submit_infos,
self.sync_objects.compute_inflight_fences[self.current_frame]
);
}
/*log compute shader invocations
unsafe {
self.device.cmd_end_query(self.compute_command_buffers[self.current_frame], query_pool, 0);
}
let query_results = unsafe {
self.device.get_query_pool_results::<u32>(
query_pool,
0, // Starting query index
1, // Number of queries to retrieve (1 in this case)
data, // Results will be stored here
//0, // Query results stride (optional)
vk::QueryResultFlags::TYPE_64, // Flags specifying the type of query results
)
.expect("Failed to retrieve query pool results"
)};
println!("Compute shader invocations: {:?}", data[0]);*/
//graphics submission
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
let (image_index, _is_sub_optimal) = unsafe {
let result = self.swapchain_stuff.swapchain_loader.acquire_next_image(
self.swapchain_stuff.swapchain,
std::u64::MAX,
self.sync_objects.image_available_semaphores[self.current_frame],
vk::Fence::null(),
);
match result {
Ok(image_index) => image_index,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR => {
SwapChainStuff::recreate_swapchain(self);
return;
}
_ => panic!("Failed to acquire Swap Chain Image!"),
},
}
};
unsafe {
self.device
.reset_fences(&[self.sync_objects.inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(
self.command_buffers[self.current_frame],
vk::CommandBufferResetFlags::empty(),
);
}
self.record_command_buffer(self.command_buffers[self.current_frame], image_index as usize);
let wait_semaphores = [
self.sync_objects.compute_finished_semaphores[self.current_frame],
self.sync_objects.image_available_semaphores[self.current_frame],
];
let wait_stages = [
vk::PipelineStageFlags::VERTEX_INPUT,
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
];
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
wait_semaphore_count: 2,
p_wait_semaphores: wait_semaphores.as_ptr(),
p_wait_dst_stage_mask: wait_stages.as_ptr(),
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
..Default::default()
}];
unsafe {
self.device
.queue_submit(
self.graphics_queue,
&submit_infos,
self.sync_objects.inflight_fences[self.current_frame],
)
.expect("failed to submit draw command buffer");
}
let swapchains = [self.swapchain_stuff.swapchain];
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PRESENT_INFO_KHR,
p_next: ptr::null(),
wait_semaphore_count: 1,
p_wait_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
swapchain_count: 1,
p_swapchains: swapchains.as_ptr(),
p_image_indices: &image_index,
p_results: ptr::null_mut(),
};
let result = unsafe {
self.swapchain_stuff.swapchain_loader
.queue_present(self.present_queue, &present_info)
};
let is_resized = match result {
Ok(_) => self.is_framebuffer_resized,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR | vk::Result::SUBOPTIMAL_KHR => true,
_ => panic!("Failed to execute queue present."),
},
};
if is_resized {
self.is_framebuffer_resized = false;
SwapChainStuff::recreate_swapchain(self);
}
//println!("resized {}", self.is_framebuffer_resized);
//log compute shader invocations
/*unsafe {
self.device.cmd_end_query(self.compute_command_buffers[self.current_frame], self.query_pool, 0);
}*/
let query_results = unsafe {
self.device.get_query_pool_results::<u64>(
self.query_pool,
0, // Starting query index
1, // Number of queries to retrieve (1 in this case)
self.query_mapped, // Results will be stored here
//0, // Query results stride (optional)
vk::QueryResultFlags::TYPE_64, // Flags specifying the type of query results
)};
println!("Compute shader invocations: {:?}", self.query_mapped[0]);
self.current_frame = (self.current_frame + 1) % MAX_FRAMES_IN_FLIGHT;
}
}

@ -27,10 +27,17 @@ void main()
Particle particleIn = particlesIn[index];
//particlesOut[index].position = particleIn.position + particleIn.velocity.xy * ubo.deltaTime;
particlesOut[index].position = particleIn.position + vec2(1.0, 1.0) * ubo.deltaTime;
particlesOut[index].position = vec2(100.0, 100.0);
particlesOut[0].position = vec2(100.0, 100.0);
//particlesOut[index].position = vec2(100, 100);
particlesOut[index].velocity = particleIn.velocity;
particlesOut[index].position = vec2(5, 5)
particlesOut[index].color = vec4(150.0, 150.0, 150.0, 150.0);
particlesOut[0].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[1].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[2].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[3].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[4].color = vec4(1.0, 1.0, 1.0, 1.0);
// Flip movement at window border
if ((particlesOut[index].position.x <= -1.0) || (particlesOut[index].position.x >= 1.0)) {

@ -7,5 +7,6 @@ layout(location = 0) out vec4 outColor;
void main() {
vec2 coord = gl_PointCoord - vec2(0.5);
outColor = vec4(fragColor, 0.5 - length(coord));
//outColor = vec4(fragColor, 0.5 - length(coord));
outColor = vec4(fragColor, 1.0);
}

@ -8,6 +8,7 @@ layout(location = 0) out vec3 fragColor;
void main() {
gl_PointSize = 14.0;
gl_Position = vec4(inPosition.xy, 1.0, 1.0);
gl_Position = vec4(inPosition, 1.0, 1.0);
fragColor = inColor.rgb;
//fragColor = vec3(1.0, 1.0, 1.0);
}

@ -2,6 +2,6 @@ pub mod constants;
pub mod debug;
pub mod fps_limiter;
pub mod platforms;
//pub mod share;
pub mod window;
pub mod structures;
pub mod tools;

@ -18,7 +18,7 @@ pub const DEVICE_EXTENSIONS: DeviceExtension = DeviceExtension {
names: ["VK_KHR_swapchain"],
};
pub const MAX_FRAMES_IN_FLIGHT: usize = 2;
pub const IS_PAINT_FPS_COUNTER: bool = true;
pub const IS_PAINT_FPS_COUNTER: bool = false;
impl DeviceExtension {
pub fn get_extensions_raw_names(&self) -> [*const c_char; 1] {

@ -8,6 +8,7 @@ use memoffset::offset_of;
use super::platforms;
use crate::render::App;
use crate::render::*;
use crate::utility::window::VulkanApp;
pub struct DeviceExtension {
pub names: [&'static str; 1],
@ -151,6 +152,11 @@ impl SwapChainStuff {
.destroy_image_view(*imageview, None)
}
}
unsafe {
self.swapchain_loader
.destroy_swapchain(self.swapchain, None)
}
}
pub fn recreate_swapchain(app: &mut App) {
@ -159,7 +165,7 @@ impl SwapChainStuff {
.device_wait_idle();
}
app.swapchain_stuff.cleanup_swapchain(&app.device);
app.cleanup_swapchain();
app.swapchain_stuff = SwapChainStuff::new(
&app.instance,
@ -170,8 +176,8 @@ impl SwapChainStuff {
&app.queue_family,
);
App::create_image_views(&app.device, &app.swapchain_stuff.swapchain_format, &app.swapchain_stuff.swapchain_images);
App::create_framebuffers(&app.device, app.render_pass, &app.swapchain_stuff.swapchain_imageviews, &app.swapchain_stuff.swapchain_extent);
app.swapchain_stuff.swapchain_imageviews = App::create_image_views(&app.device, &app.swapchain_stuff.swapchain_format, &app.swapchain_stuff.swapchain_images);
app.swapchain_stuff.swapchain_framebuffers = App::create_framebuffers(&app.device, app.render_pass, &app.swapchain_stuff.swapchain_imageviews, &app.swapchain_stuff.swapchain_extent);
}
pub fn choose_swapchain_extent(

@ -0,0 +1,91 @@
use winit::event::{Event, VirtualKeyCode, ElementState, KeyboardInput, WindowEvent};
use winit::event_loop::{EventLoop, ControlFlow};
const IS_PAINT_FPS_COUNTER: bool = true;
pub fn init_window(
event_loop: &EventLoop<()>,
title: &str,
width: u32,
height: u32,
) -> winit::window::Window {
winit::window::WindowBuilder::new()
.with_title(title)
.with_inner_size(winit::dpi::LogicalSize::new(width, height))
.build(event_loop)
.expect("Failed to create window.")
}
pub trait VulkanApp {
fn draw_frame(&mut self);
fn recreate_swapchain(&mut self);
fn cleanup_swapchain(&self);
fn wait_device_idle(&self);
fn resize_framebuffer(&mut self);
fn window_ref(&self) -> &winit::window::Window;
}
pub struct ProgramProc {
pub event_loop: EventLoop<()>,
}
impl ProgramProc {
pub fn new() -> ProgramProc {
ProgramProc { event_loop: EventLoop::new() }
}
pub fn main_loop<A: 'static + VulkanApp>(self, mut vulkan_app: A) {
let mut tick_counter = super::fps_limiter::FPSLimiter::new();
self.event_loop
.run(move |event, _, control_flow| {/*println!("evl");*/match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
}
WindowEvent::KeyboardInput { input, .. } => match input {
KeyboardInput {
virtual_keycode,
state,
..
} => match (virtual_keycode, state) {
(Some(VirtualKeyCode::Escape), ElementState::Pressed) => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
}
_ => {}
},
},
WindowEvent::Resized(_new_size) => {
println!("resizing framebuffer event");
vulkan_app.wait_device_idle();
vulkan_app.resize_framebuffer();
}
_ => {}
},
Event::MainEventsCleared => {
vulkan_app.window_ref().request_redraw();
}
Event::RedrawRequested(_window_id) => {
//println!("redraw req");
let delta_time = tick_counter.delta_time();
vulkan_app.draw_frame();
//println!("frame drawn!");
if IS_PAINT_FPS_COUNTER {
print!("FPS: {}\r", tick_counter.fps());
}
tick_counter.tick_frame();
}
Event::LoopDestroyed => {
vulkan_app.wait_device_idle();
}
_ => (),
}})
}
}
Loading…
Cancel
Save