From 0661494b0f152d130794406942cad1f9a3a113a5 Mon Sep 17 00:00:00 2001 From: Lucas Vas Date: Fri, 8 May 2026 16:51:18 -0400 Subject: [PATCH] style: rustfmt run --- .idea/encodings.xml | 4 +- src/app.rs | 251 ++++++++++++++++++++++------------------- src/common/instance.rs | 2 +- src/common/mod.rs | 2 +- src/common/scene.rs | 19 ++-- src/gpu/instance.rs | 2 +- src/gpu/mod.rs | 2 +- src/gpu/vertex3.rs | 10 +- src/main.rs | 10 +- src/math/matrix2.rs | 14 +-- src/math/matrix3.rs | 1 + src/math/matrix4.rs | 39 +++++-- src/math/mod.rs | 18 +-- src/math/traits.rs | 31 +++-- src/math/vector2.rs | 12 +- src/math/vector3.rs | 22 +--- src/math/vector4.rs | 47 +++----- 17 files changed, 259 insertions(+), 227 deletions(-) diff --git a/.idea/encodings.xml b/.idea/encodings.xml index df87cf9..95c926b 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -1,4 +1,6 @@ - + + + \ No newline at end of file diff --git a/src/app.rs b/src/app.rs index 7ead46b..8db215a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,36 +1,45 @@ -use std::error::Error; +use crate::common::mesh::MeshRegistry; +use crate::gpu::vertex3::Vertex3; +use crate::triangle; +use std::error::Error; use std::sync::Arc; use vulkano::buffer::{Buffer, BufferCreateInfo, BufferUsage, Subbuffer}; -use vulkano::command_buffer::allocator::{StandardCommandBufferAllocator, StandardCommandBufferAllocatorCreateInfo}; -use vulkano::command_buffer::{AutoCommandBufferBuilder, CommandBufferUsage, PrimaryAutoCommandBuffer, RenderPassBeginInfo, SubpassBeginInfo, SubpassContents, SubpassEndInfo}; +use vulkano::command_buffer::allocator::{ + StandardCommandBufferAllocator, StandardCommandBufferAllocatorCreateInfo, +}; +use vulkano::command_buffer::{ + AutoCommandBufferBuilder, CommandBufferUsage, PrimaryAutoCommandBuffer, RenderPassBeginInfo, + SubpassBeginInfo, SubpassContents, SubpassEndInfo, +}; use vulkano::descriptor_set::allocator::{DescriptorSetAllocator, StandardDescriptorSetAllocator}; -use vulkano::device::{Device, DeviceCreateInfo, DeviceExtensions, Queue, QueueCreateInfo, QueueFlags}; use vulkano::device::physical::{PhysicalDevice, PhysicalDeviceType}; -use vulkano::image::{Image, ImageUsage}; +use vulkano::device::{ + Device, DeviceCreateInfo, DeviceExtensions, Queue, QueueCreateInfo, QueueFlags, +}; use vulkano::image::view::ImageView; +use vulkano::image::{Image, ImageUsage}; use vulkano::instance::{Instance, InstanceCreateFlags, InstanceCreateInfo, InstanceExtensions}; -use vulkano::memory::allocator::{AllocationCreateInfo, MemoryAllocator, MemoryTypeFilter, StandardMemoryAllocator}; -use vulkano::pipeline::{GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo}; -use vulkano::pipeline::graphics::color_blend::{ColorBlendAttachmentState, ColorBlendState}; +use vulkano::memory::allocator::{ + AllocationCreateInfo, MemoryAllocator, MemoryTypeFilter, StandardMemoryAllocator, +}; use vulkano::pipeline::graphics::GraphicsPipelineCreateInfo; +use vulkano::pipeline::graphics::color_blend::{ColorBlendAttachmentState, ColorBlendState}; use vulkano::pipeline::graphics::input_assembly::InputAssemblyState; use vulkano::pipeline::graphics::multisample::MultisampleState; use vulkano::pipeline::graphics::rasterization::RasterizationState; use vulkano::pipeline::graphics::vertex_input::{Vertex, VertexDefinition}; use vulkano::pipeline::graphics::viewport::{Viewport, ViewportState}; use vulkano::pipeline::layout::PipelineDescriptorSetLayoutCreateInfo; +use vulkano::pipeline::{GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo}; use vulkano::render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass, Subpass}; -use vulkano::swapchain::{Surface, Swapchain, SwapchainCreateInfo, SwapchainPresentInfo}; -use vulkano::{swapchain, sync, Validated, VulkanError, VulkanLibrary}; use vulkano::shader::ShaderModule; +use vulkano::swapchain::{Surface, Swapchain, SwapchainCreateInfo, SwapchainPresentInfo}; use vulkano::sync::GpuFuture; +use vulkano::{Validated, VulkanError, VulkanLibrary, swapchain, sync}; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::ActiveEventLoop; use winit::window::{Window, WindowAttributes, WindowId}; -use crate::common::mesh::MeshRegistry; -use crate::gpu::vertex3::Vertex3; -use crate::triangle; struct VulkanContext { window: Arc, @@ -54,7 +63,10 @@ impl VulkanContext { /// Initializes and returns a new `VulkanContext`. It may fail in all cases where a Vulkan object /// may fail, specifically during initialization of shaders, devices, buffers, or any other such /// structures. - pub fn init(instance: Arc, event_loop: &ActiveEventLoop) -> Result> { + pub fn init( + instance: Arc, + event_loop: &ActiveEventLoop, + ) -> Result> { let attributes = WindowAttributes::default() .with_title("Vulkano Example") .with_resizable(true); @@ -70,41 +82,29 @@ impl VulkanContext { // Get a physical device. Fails if there is no suitable device found. The device must have a // graphics queue and swapchain capabilities. - let (physical_device, queue_family_idx) = Self::get_physical_device( - instance.clone(), - surface.clone(), - &dev_extensions - )?; + let (physical_device, queue_family_idx) = + Self::get_physical_device(instance.clone(), surface.clone(), &dev_extensions)?; // Create a Vulkan device. This is a handle to the connection between the program and the // chosen physical device. let (device, mut queues) = Self::create_device( physical_device.clone(), &dev_extensions, - queue_family_idx as usize + queue_family_idx as usize, )?; // Get the first queue. This is what we'll use for drawing. - let queue = queues.next() - .ok_or("Queues list was empty.")?; + let queue = queues.next().ok_or("Queues list was empty.")?; - let capabilities = physical_device - .surface_capabilities( - &surface, - Default::default() - )?; + let capabilities = physical_device.surface_capabilities(&surface, Default::default())?; - let dimensions = window - .inner_size(); + let dimensions = window.inner_size(); let composite_alpha = capabilities .supported_composite_alpha .into_iter() .next() .ok_or("No composite alpha supported")?; - let image_format = physical_device - .surface_formats(&surface, Default::default())? - [0] - .0; + let image_format = physical_device.surface_formats(&surface, Default::default())?[0].0; // Swapchain needs to be easily changeable, since resizing the window creates a whole new // set of information. Putting this into a function would be good, but also the new @@ -119,7 +119,7 @@ impl VulkanContext { image_usage: ImageUsage::COLOR_ATTACHMENT, composite_alpha, ..Default::default() - } + }, )?; let mem_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); @@ -127,7 +127,10 @@ impl VulkanContext { device.clone(), StandardCommandBufferAllocatorCreateInfo::default(), )); - let desc_allocator = Arc::new(StandardDescriptorSetAllocator::new(device.clone(), Default::default())); + let desc_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); let render_pass = vulkano::single_pass_renderpass!( device.clone(), @@ -158,7 +161,7 @@ impl VulkanContext { &vert_shader, &frag_shader, &render_pass, - [image_extents[0] as f32, image_extents[1] as f32] + [image_extents[0] as f32, image_extents[1] as f32], )?; let vertex_buffer = Arc::new(Buffer::from_iter( @@ -173,11 +176,19 @@ impl VulkanContext { ..Default::default() }, vec![ - Vertex3 { position: [0.5, 0.5, 0.0] }, - Vertex3 { position: [-0.5, 0.5, 0.0] }, - Vertex3 { position: [-0.5, -0.5, 0.0] }, - Vertex3 { position: [0.5, -0.5, 0.0] }, - ] + Vertex3 { + position: [0.5, 0.5, 0.0], + }, + Vertex3 { + position: [-0.5, 0.5, 0.0], + }, + Vertex3 { + position: [-0.5, -0.5, 0.0], + }, + Vertex3 { + position: [0.5, -0.5, 0.0], + }, + ], )?); let index_buffer = Arc::new(Buffer::from_iter( @@ -191,10 +202,7 @@ impl VulkanContext { | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - vec![ - 0, 1, 2, - 0, 2, 3, - ] + vec![0, 1, 2, 0, 2, 3], )?); let cmd_buffers = Self::get_command_buffers( @@ -203,12 +211,10 @@ impl VulkanContext { &pipeline, &framebuffers, &vertex_buffer, - &index_buffer + &index_buffer, )?; - let mesh_registry = Arc::new(MeshRegistry::new( - mem_allocator.clone(), - )?); + let mesh_registry = Arc::new(MeshRegistry::new(mem_allocator.clone())?); Ok(Self { window, @@ -233,7 +239,8 @@ impl VulkanContext { pub fn draw_frame(&mut self) -> Result<(), Box> { let (image_idx, suboptimal, acquire_future) = match swapchain::acquire_next_image(self.swapchain.clone(), None) - .map_err(Validated::unwrap){ + .map_err(Validated::unwrap) + { Ok(r) => r, Err(VulkanError::OutOfDate) => { println!("Swapchain is out of date!"); @@ -252,7 +259,10 @@ impl VulkanContext { let execution = sync::now(self.device.clone()) .join(acquire_future) - .then_execute(self.queue.clone(), self.cmd_buffers[image_idx as usize].clone())? + .then_execute( + self.queue.clone(), + self.cmd_buffers[image_idx as usize].clone(), + )? .then_swapchain_present( self.queue.clone(), SwapchainPresentInfo::swapchain_image_index(self.swapchain.clone(), image_idx), @@ -269,7 +279,7 @@ impl VulkanContext { fn get_physical_device( instance: Arc, surface: Arc, - extensions: &DeviceExtensions + extensions: &DeviceExtensions, ) -> Result<(Arc, u32), String> { instance .enumerate_physical_devices() @@ -285,12 +295,10 @@ impl VulkanContext { }) .map(|q| (dev, q as u32)) }) - .min_by_key(|(dev, _)| { - match dev.properties().device_type { - PhysicalDeviceType::DiscreteGpu => 0, - PhysicalDeviceType::Cpu => 1, - _ => 2 - } + .min_by_key(|(dev, _)| match dev.properties().device_type { + PhysicalDeviceType::DiscreteGpu => 0, + PhysicalDeviceType::Cpu => 1, + _ => 2, }) .ok_or_else(|| "No physical devices found".to_string()) } @@ -299,7 +307,7 @@ impl VulkanContext { fn create_device( physical_device: Arc, device_extensions: &DeviceExtensions, - graphics_index: usize + graphics_index: usize, ) -> Result<(Arc, impl ExactSizeIterator>), String> { Device::new( physical_device.clone(), @@ -310,17 +318,18 @@ impl VulkanContext { }], enabled_extensions: device_extensions.clone(), ..Default::default() - } + }, ) - .map_err(|e| format!("Failed to create device: {e}")) + .map_err(|e| format!("Failed to create device: {e}")) } /// Creates a new [`Framebuffer`] for each swapchain image. fn create_framebuffers( images: &Vec>, - render_pass: &Arc + render_pass: &Arc, ) -> Result>, Box> { - let framebuffers = images.iter() + let framebuffers = images + .iter() .map(|image| { let view = ImageView::new_default(image.clone()).unwrap(); @@ -329,9 +338,9 @@ impl VulkanContext { FramebufferCreateInfo { attachments: vec![view], ..Default::default() - } + }, ) - .unwrap() + .unwrap() }) .collect::>>(); @@ -348,26 +357,27 @@ impl VulkanContext { extents: [f32; 2], ) -> Result, Box> { // Get shader stages - let vs = vert_shader.entry_point("main") + let vs = vert_shader + .entry_point("main") .ok_or("Failed to find vertex shader entry point")?; - let fs = frag_shader.entry_point("main") + let fs = frag_shader + .entry_point("main") .ok_or("Failed to find fragment shader entry point")?; - let vertex_input_state = Vertex3::per_vertex() - .definition(&vs)?; + let vertex_input_state = Vertex3::per_vertex().definition(&vs)?; let stages = vec![ PipelineShaderStageCreateInfo::new(vs), PipelineShaderStageCreateInfo::new(fs), ]; - let subpass = Subpass::from(render_pass.clone(), 0) - .ok_or("Failed to create pipeline subpass")?; + let subpass = + Subpass::from(render_pass.clone(), 0).ok_or("Failed to create pipeline subpass")?; let layout = PipelineLayout::new( device.clone(), PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(device.clone())? + .into_pipeline_layout_create_info(device.clone())?, )?; let viewport = Viewport { @@ -392,12 +402,12 @@ impl VulkanContext { multisample_state: Some(MultisampleState::default()), color_blend_state: Some(ColorBlendState::with_attachment_states( subpass.num_color_attachments(), - ColorBlendAttachmentState::default() + ColorBlendAttachmentState::default(), )), dynamic_state: Default::default(), subpass: Some(subpass.into()), ..GraphicsPipelineCreateInfo::layout(layout) - } + }, )?) } @@ -408,15 +418,17 @@ impl VulkanContext { pipeline: &Arc, framebuffers: &Vec>, vertex_buffer: &Arc>, - index_buffer: &Subbuffer<[u32]> + index_buffer: &Subbuffer<[u32]>, ) -> Result>, Box> { - let buffers = framebuffers.iter() + let buffers = framebuffers + .iter() .filter_map(|framebuffer| { let mut builder = AutoCommandBufferBuilder::primary( cmd_allocator.clone(), queue.queue_family_index(), - CommandBufferUsage::MultipleSubmit - ).ok()?; + CommandBufferUsage::MultipleSubmit, + ) + .ok()?; unsafe { builder @@ -428,14 +440,20 @@ impl VulkanContext { SubpassBeginInfo { contents: SubpassContents::Inline, ..Default::default() - } - ).ok()? - .bind_pipeline_graphics(pipeline.clone()).ok()? - .bind_vertex_buffers(0, vertex_buffer.as_ref().clone()).ok()? - .bind_index_buffer(index_buffer.clone()).ok()? + }, + ) + .ok()? + .bind_pipeline_graphics(pipeline.clone()) + .ok()? + .bind_vertex_buffers(0, vertex_buffer.as_ref().clone()) + .ok()? + .bind_index_buffer(index_buffer.clone()) + .ok()? // .draw(vertex_buffer.len() as u32, 1, 0, 0).ok()? - .draw_indexed(index_buffer.len() as u32, 1, 0, 0, 0).ok()? - .end_render_pass(SubpassEndInfo::default()).ok()?; + .draw_indexed(index_buffer.len() as u32, 1, 0, 0, 0) + .ok()? + .end_render_pass(SubpassEndInfo::default()) + .ok()?; } builder.build().ok() @@ -450,19 +468,21 @@ impl VulkanContext { /// specifically the [`GraphicsPipeline`] and [`PrimaryAutoCommandBuffer`]. All information is /// automatically set within the `VulkanContext`. pub fn recreate_swapchain(&mut self, resized: bool) -> Result<(), Box> { - unsafe { self.device.wait_idle()?; }; + unsafe { + self.device.wait_idle()?; + }; - let (new_swapchain, new_images) = self.swapchain - .recreate(SwapchainCreateInfo { - image_extent: self.window.inner_size().into(), - ..self.swapchain.create_info() - })?; + let (new_swapchain, new_images) = self.swapchain.recreate(SwapchainCreateInfo { + image_extent: self.window.inner_size().into(), + ..self.swapchain.create_info() + })?; self.swapchain = new_swapchain; self.swapchain_images = new_images; // Recreate the framebuffers, which depend on the swapchain. - let new_framebuffers = Self::create_framebuffers(&self.swapchain_images, &self.render_pass)?; + let new_framebuffers = + Self::create_framebuffers(&self.swapchain_images, &self.render_pass)?; self.framebuffers = new_framebuffers; @@ -482,7 +502,7 @@ impl VulkanContext { &new_pipeline, &self.framebuffers, &self.mesh_registry.vertex_buffer, - &self.mesh_registry.index_buffer + &self.mesh_registry.index_buffer, )?; self.pipeline = new_pipeline; @@ -517,11 +537,9 @@ impl MainApplication { } /// Gets the Vulkan instance. - fn get_instance( - required_extensions: InstanceExtensions, - ) -> Result, String> { - let library = VulkanLibrary::new() - .map_err(|e| format!("Failed to find Vulkan library: {e}"))?; + fn get_instance(required_extensions: InstanceExtensions) -> Result, String> { + let library = + VulkanLibrary::new().map_err(|e| format!("Failed to find Vulkan library: {e}"))?; Instance::new( library, @@ -529,36 +547,43 @@ impl MainApplication { flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, enabled_extensions: required_extensions, ..Default::default() - } + }, ) - .map_err(|e| format!("Failed to create instance: {e}")) + .map_err(|e| format!("Failed to create instance: {e}")) } } impl ApplicationHandler for MainApplication { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - self.context.is_none() - .then(|| { - // Initialization logic - let context = VulkanContext::init( - self.instance.clone(), - event_loop - ).expect("Couldn't initialize VulkanContext"); + self.context.is_none().then(|| { + // Initialization logic + let context = VulkanContext::init(self.instance.clone(), event_loop) + .expect("Couldn't initialize VulkanContext"); - self.context = Some(context); - }); + self.context = Some(context); + }); } - fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) { + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ) { match event { WindowEvent::CloseRequested => { println!("Closing window."); event_loop.exit(); } WindowEvent::Resized(dimensions) => { - println!("Window was resized, recreating swapchain. New dimensions: {:?}", dimensions); + println!( + "Window was resized, recreating swapchain. New dimensions: {:?}", + dimensions + ); if let Some(context) = self.context.as_mut() { - context.recreate_swapchain(true).expect("Failed to recreate swapchain"); + context + .recreate_swapchain(true) + .expect("Failed to recreate swapchain"); } } WindowEvent::RedrawRequested => { @@ -569,7 +594,7 @@ impl ApplicationHandler for MainApplication { // Queue the next frame for drawing. self.context.as_ref().unwrap().window.request_redraw(); } - _ => () + _ => (), } } } diff --git a/src/common/instance.rs b/src/common/instance.rs index 1f42e27..3650131 100644 --- a/src/common/instance.rs +++ b/src/common/instance.rs @@ -1,5 +1,5 @@ -use nalgebra::{Matrix4, Vector3, Vector4}; use crate::common::scene::SceneInstance; +use nalgebra::{Matrix4, Vector3, Vector4}; /// Contains all information about an instance of a mesh, specifically its translation, rotation, /// and scale. Note that the rotation is a [`Vector4`], and not a `Quaternion`. diff --git a/src/common/mod.rs b/src/common/mod.rs index 67f38a0..bdf8973 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,3 +1,3 @@ +pub mod instance; pub mod mesh; pub mod scene; -pub mod instance; diff --git a/src/common/scene.rs b/src/common/scene.rs index 6506b7f..7998a1b 100644 --- a/src/common/scene.rs +++ b/src/common/scene.rs @@ -1,7 +1,7 @@ +use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Read; use std::path::Path; -use serde::{Deserialize, Serialize}; /// A scene, which holds all information required to render a world. /// @@ -26,16 +26,15 @@ pub struct Scene { impl Scene { /// Converts this `Scene` into its byte representation. pub fn bytes(&self) -> Vec { - postcard::to_allocvec(self) - .expect("Couldn't serialize scene") + postcard::to_allocvec(self).expect("Couldn't serialize scene") } /// Reads a `scene` from the given path. Automatically resolves all paths for the meshes that /// are referenced in the struct. - /// + /// /// Reading a scene file allows for all meshes to be loaded at once, which therefore allows /// the program to allocate pipeline buffers just once during the load of this. It would likely - /// be reasonable to create a `MeshRegistry` and `InstanceRegistry` at the same time, with + /// be reasonable to create a `MeshRegistry` and `InstanceRegistry` at the same time, with /// respect to a single loaded `Scene`. pub fn from_file>(path: P) -> Self { let path = path.as_ref(); @@ -43,18 +42,20 @@ impl Scene { let mut contents = Vec::new(); let _ = file.read_to_end(&mut contents).unwrap(); - let mut scene: Self = postcard::from_bytes(contents.as_slice()) - .expect("Couldn't deserialize scene"); + let mut scene: Self = + postcard::from_bytes(contents.as_slice()).expect("Couldn't deserialize scene"); let base = path.parent().unwrap_or(&Path::new(".")); - scene.mesh_paths = scene.mesh_paths + scene.mesh_paths = scene + .mesh_paths .into_iter() .map(|(id, mesh_path)| { let res = base.join(mesh_path); let str = res.to_str().unwrap_or_default(); (id, str.to_string()) - }).collect::>(); + }) + .collect::>(); scene } diff --git a/src/gpu/instance.rs b/src/gpu/instance.rs index 229760a..a96c9eb 100644 --- a/src/gpu/instance.rs +++ b/src/gpu/instance.rs @@ -1,6 +1,6 @@ +use crate::common::instance::MeshInstance; use vulkano::buffer::BufferContents; use vulkano::pipeline::graphics::vertex_input::Vertex; -use crate::common::instance::MeshInstance; /// A transformation matrix for a mesh that can be passed into the shaders. #[derive(BufferContents, Vertex)] diff --git a/src/gpu/mod.rs b/src/gpu/mod.rs index c442b22..239ca7e 100644 --- a/src/gpu/mod.rs +++ b/src/gpu/mod.rs @@ -1,2 +1,2 @@ -pub mod vertex3; pub mod instance; +pub mod vertex3; diff --git a/src/gpu/vertex3.rs b/src/gpu/vertex3.rs index 561fdaa..e3615e2 100644 --- a/src/gpu/vertex3.rs +++ b/src/gpu/vertex3.rs @@ -1,15 +1,17 @@ use vulkano::buffer::BufferContents; use vulkano::pipeline::graphics::vertex_input::Vertex; -#[derive(Debug, BufferContents, Vertex)] +#[derive(Debug, Clone, BufferContents, Vertex)] #[repr(C)] pub struct Vertex3 { #[format(R32G32B32_SFLOAT)] pub(crate) position: [f32; 3], } -impl From<&[f32; 3]> for Vertex3 { - fn from(v: &[f32; 3]) -> Self { - Self { position: v.clone() } +impl From<[f32; 3]> for Vertex3 { + fn from(v: [f32; 3]) -> Self { + Self { + position: v.clone(), + } } } diff --git a/src/main.rs b/src/main.rs index 8030ae8..0c15f7d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,30 +1,30 @@ mod app; -pub mod math; mod common; pub mod gpu; +// pub mod math; +use crate::app::MainApplication; use std::error::Error; use vulkano::swapchain::Surface; use winit::event_loop::{ControlFlow, EventLoop}; -use crate::app::MainApplication; // Compute shader compilation. Happens at runtime, but file contents are included during compilation. mod cs { - vulkano_shaders::shader!{ + vulkano_shaders::shader! { ty: "compute", path: "src/shaders/comp.glsl", } } mod mandelbrot_shader { - vulkano_shaders::shader!{ + vulkano_shaders::shader! { ty: "compute", path: "src/shaders/mandelbrot.glsl" } } mod triangle { - vulkano_shaders::shader!{ + vulkano_shaders::shader! { shaders: { vertex: { ty: "vertex", diff --git a/src/math/matrix2.rs b/src/math/matrix2.rs index b4aafd3..464f426 100644 --- a/src/math/matrix2.rs +++ b/src/math/matrix2.rs @@ -1,6 +1,6 @@ -use std::ops::{Add, Index, IndexMut, Mul, Sub}; +use crate::math::Vector2; use crate::math::traits::{Matrix, Vector}; -use crate::math::{Vector2}; +use std::ops::{Add, Index, IndexMut, Mul, Sub}; #[derive(Clone, Debug, PartialEq, PartialOrd, Copy, Default)] pub struct Matrix2 { @@ -14,17 +14,11 @@ impl Matrix2 { } pub fn row_vector(&self, row: usize) -> Vector2 { - Vector2::from([ - self[row][0], - self[row][1], - ]) + Vector2::from([self[row][0], self[row][1]]) } pub fn column_vector(&self, col: usize) -> Vector2 { - Vector2::from([ - self[0][col], - self[1][col], - ]) + Vector2::from([self[0][col], self[1][col]]) } } diff --git a/src/math/matrix3.rs b/src/math/matrix3.rs index e69de29..8b13789 100644 --- a/src/math/matrix3.rs +++ b/src/math/matrix3.rs @@ -0,0 +1 @@ + diff --git a/src/math/matrix4.rs b/src/math/matrix4.rs index 2a7afbb..0128546 100644 --- a/src/math/matrix4.rs +++ b/src/math/matrix4.rs @@ -1,6 +1,6 @@ -use std::ops::{Add, Div, Mul, Sub}; -use crate::math::traits::{Matrix, Vector}; use crate::math::Vector4; +use crate::math::traits::{Matrix, Vector}; +use std::ops::{Add, Div, Mul, Sub}; #[derive(Debug, Clone, Default, Copy, PartialEq)] pub struct Matrix4 { @@ -10,8 +10,7 @@ pub struct Matrix4 { row4: Vector4, } -impl Matrix4 { -} +impl Matrix4 {} impl Add for Matrix4 { type Output = Self; @@ -68,10 +67,34 @@ impl Mul for Matrix4 { fn mul(self, rhs: Self) -> Self { let rhs = rhs.transpose(); Self { - row1: [self.row1.dot(rhs.row1), self.row1.dot(rhs.row2), self.row1.dot(rhs.row3), self.row1.dot(rhs.row4)].into(), - row2: [self.row2.dot(rhs.row1), self.row2.dot(rhs.row2), self.row2.dot(rhs.row3), self.row2.dot(rhs.row4)].into(), - row3: [self.row3.dot(rhs.row1), self.row3.dot(rhs.row2), self.row3.dot(rhs.row3), self.row3.dot(rhs.row4)].into(), - row4: [self.row4.dot(rhs.row1), self.row4.dot(rhs.row2), self.row4.dot(rhs.row3), self.row4.dot(rhs.row4)].into(), + row1: [ + self.row1.dot(rhs.row1), + self.row1.dot(rhs.row2), + self.row1.dot(rhs.row3), + self.row1.dot(rhs.row4), + ] + .into(), + row2: [ + self.row2.dot(rhs.row1), + self.row2.dot(rhs.row2), + self.row2.dot(rhs.row3), + self.row2.dot(rhs.row4), + ] + .into(), + row3: [ + self.row3.dot(rhs.row1), + self.row3.dot(rhs.row2), + self.row3.dot(rhs.row3), + self.row3.dot(rhs.row4), + ] + .into(), + row4: [ + self.row4.dot(rhs.row1), + self.row4.dot(rhs.row2), + self.row4.dot(rhs.row3), + self.row4.dot(rhs.row4), + ] + .into(), } } } diff --git a/src/math/mod.rs b/src/math/mod.rs index e1ee07d..5e424ad 100644 --- a/src/math/mod.rs +++ b/src/math/mod.rs @@ -1,14 +1,14 @@ -mod matrix4; -mod vector3; -mod vector2; -mod traits; -mod matrix3; mod matrix2; +mod matrix3; +mod matrix4; +mod traits; +mod vector2; +mod vector3; mod vector4; -pub use matrix4::*; -pub use matrix3::*; pub use matrix2::*; -pub use vector4::*; +pub use matrix3::*; +pub use matrix4::*; +pub use vector2::*; pub use vector3::*; -pub use vector2::*; \ No newline at end of file +pub use vector4::*; diff --git a/src/math/traits.rs b/src/math/traits.rs index 369ff3b..a366a7f 100644 --- a/src/math/traits.rs +++ b/src/math/traits.rs @@ -1,8 +1,17 @@ -use std::ops::{Add, Div, Mul, Sub}; use crate::math::Vector4; +use std::ops::{Add, Div, Mul, Sub}; -pub trait Vector: Clone + Copy + Default + PartialEq + Add + Sub + PartialOrd - + Div + Mul { +pub trait Vector: + Clone + + Copy + + Default + + PartialEq + + Add + + Sub + + PartialOrd + + Div + + Mul +{ /// Gets the dot product of the two vectors. fn dot(self, other: Self) -> f32; @@ -36,14 +45,22 @@ pub trait Vector: Clone + Copy + Default + PartialEq + Add + Sub + PartialOrd /// Note that this trait does not require implementation of the `Div` trait at all - this is because /// matrices do not have division, only multiplication by a scalar value. This doesn't mean that the /// scalar cannot be a decimal value, however. -pub trait Matrix: Clone + Copy + Default + PartialEq + Add + Sub - + Mul + Mul +pub trait Matrix: + Clone + + Copy + + Default + + PartialEq + + Add + + Sub + + Mul + + Mul + Mul -where TVec: Vector +where + TVec: Vector, { /// Creates an identity matrix. fn identity() -> Self; - + /// Gets the transpose of this matrix. fn transpose(&self) -> Self; diff --git a/src/math/vector2.rs b/src/math/vector2.rs index a0715f2..5c15744 100644 --- a/src/math/vector2.rs +++ b/src/math/vector2.rs @@ -1,5 +1,5 @@ -use std::ops::{Add, Div, Mul, Sub, Index, IndexMut}; use crate::math::traits::Vector; +use std::ops::{Add, Div, Index, IndexMut, Mul, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq, PartialOrd)] pub struct Vector2 { @@ -118,18 +118,12 @@ impl Vector for Vector2 { impl From<[f32; 2]> for Vector2 { fn from(v: [f32; 2]) -> Self { - Self { - x: v[0], - y: v[1], - } + Self { x: v[0], y: v[1] } } } impl From for Vector2 { fn from(v: f32) -> Self { - Self { - x: v, - y: 0.0, - } + Self { x: v, y: 0.0 } } } diff --git a/src/math/vector3.rs b/src/math/vector3.rs index bc74bdf..e992b77 100644 --- a/src/math/vector3.rs +++ b/src/math/vector3.rs @@ -1,6 +1,6 @@ -use std::ops::{Add, Div, Mul, Sub}; use crate::math::traits::Vector; use crate::math::vector2::Vector2; +use std::ops::{Add, Div, Mul, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq, PartialOrd)] pub struct Vector3 { @@ -15,24 +15,15 @@ impl Vector3 { } pub fn xy(&self) -> Vector2 { - Vector2::from([ - self.x, - self.y - ]) + Vector2::from([self.x, self.y]) } pub fn yz(&self) -> Vector2 { - Vector2::from([ - self.y, - self.z - ]) + Vector2::from([self.y, self.z]) } pub fn xz(&self) -> Vector2 { - Vector2::from([ - self.x, - self.z - ]) + Vector2::from([self.x, self.z]) } pub fn xyz(&self) -> (f32, f32, f32) { @@ -144,9 +135,6 @@ impl From<[f32; 3]> for Vector3 { impl From for Vector3 { fn from(v: Vector2) -> Self { - Self { - z: 0.0, - ..v.into() - } + Self { z: 0.0, ..v.into() } } } diff --git a/src/math/vector4.rs b/src/math/vector4.rs index 28eb0f2..d14c510 100644 --- a/src/math/vector4.rs +++ b/src/math/vector4.rs @@ -1,6 +1,6 @@ -use std::ops::{Add, Div, Mul, Sub}; use crate::math::traits::Vector; use crate::math::{Vector2, Vector3}; +use std::ops::{Add, Div, Mul, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq, PartialOrd)] pub struct Vector4 { @@ -11,17 +11,10 @@ pub struct Vector4 { } impl Vector4 { - pub fn new( - x: f32, - y: f32, - z: f32, - w: f32, - ) -> Self { - Self { - x, y, z, w - } + pub fn new(x: f32, y: f32, z: f32, w: f32) -> Self { + Self { x, y, z, w } } - + pub fn one() -> Self { Self { x: 1.0, @@ -30,7 +23,7 @@ impl Vector4 { w: 1.0, } } - + pub fn xyzw(&self) -> (f32, f32, f32, f32) { (self.x, self.y, self.z, self.w) } @@ -38,15 +31,15 @@ impl Vector4 { pub fn xyz(&self) -> Vector3 { Vector3::from([self.x, self.y, self.z]) } - + pub fn xy(&self) -> Vector2 { Vector2::from([self.x, self.y]) } - + pub fn yz(&self) -> Vector2 { Vector2::from([self.y, self.z]) } - + pub fn xz(&self) -> Vector2 { Vector2::from([self.x, self.z]) } @@ -54,7 +47,7 @@ impl Vector4 { impl Add for Vector4 { type Output = Self; - + fn add(self, other: Self) -> Self { Self { x: self.x + other.x, @@ -67,7 +60,7 @@ impl Add for Vector4 { impl Sub for Vector4 { type Output = Self; - + fn sub(self, other: Self) -> Self { Self { x: self.x - other.x, @@ -80,7 +73,7 @@ impl Sub for Vector4 { impl Mul for Vector4 { type Output = Self; - + fn mul(self, rhs: f32) -> Self::Output { Self { x: self.x * rhs, @@ -93,7 +86,7 @@ impl Mul for Vector4 { impl Mul for f32 { type Output = Vector4; - + fn mul(self, rhs: Vector4) -> Self::Output { rhs * self } @@ -128,7 +121,7 @@ impl Div for Vector4 { impl Div for f32 { type Output = Vector4; - + fn div(self, rhs: Vector4) -> Self::Output { rhs / self } @@ -150,28 +143,20 @@ impl Vector for Vector4 { impl From<[f32; 4]> for Vector4 { fn from([x, y, z, w]: [f32; 4]) -> Self { - Self { - x, y, z, w, - } + Self { x, y, z, w } } } impl From<[f32; 3]> for Vector4 { /// Creates a homogenous `Vector4` from a 3D positional vector. fn from([x, y, z]: [f32; 3]) -> Self { - Self { - x, y, z, - w: 1.0, - } + Self { x, y, z, w: 1.0 } } } impl From for Vector4 { fn from(Vector3 { x, y, z }: Vector3) -> Self { - Self { - x, y, z, - w: 1.0 - } + Self { x, y, z, w: 1.0 } } }