misc: ran clippy

This commit is contained in:
2023-11-15 01:50:08 +02:00
parent fac31bf3d5
commit 9ffac336d1
12 changed files with 106 additions and 111 deletions
+3 -3
View File
@@ -61,7 +61,7 @@ impl AABB {
},
];
let indices = vec![
let indices = [
0, 1, 2, 2, 3, 0, // front
1, 5, 6, 6, 2, 1, // right
5, 4, 7, 7, 6, 5, // back
@@ -88,7 +88,7 @@ impl AABB {
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo);
gl::BufferData(
gl::ELEMENT_ARRAY_BUFFER,
(std::mem::size_of::<u32>() * indices.len() as usize) as isize,
(std::mem::size_of::<u32>() * indices.len()) as isize,
indices.as_ptr() as *const std::ffi::c_void,
gl::STATIC_DRAW,
);
@@ -142,7 +142,7 @@ impl AABB {
pub fn draw(&self, shader: &Shader, model_mat: &glm::Mat4) {
shader.use_shader();
shader.set_mat4fv("model", &model_mat);
shader.set_mat4fv("model", model_mat);
shader.set_3fv("material.ambient", glm::vec3(1.0, 0.627, 0.157));
shader.set_3fv("material.diffuse", glm::vec3(1.0, 0.627, 0.157));
+4 -2
View File
@@ -14,8 +14,8 @@ pub struct Camera {
pub fov: f32,
}
impl Camera {
pub fn new() -> Camera {
impl Default for Camera {
fn default() -> Self {
Camera {
position: glm::vec3(0.0, 3.0, 3.0),
front: glm::vec3(0.0, 0.0, -1.0),
@@ -28,7 +28,9 @@ impl Camera {
fov: 45.0,
}
}
}
impl Camera {
pub fn handle_mouse_scroll(&mut self, yoffset: f32, can_capture_cursor: bool, fov_zoom: bool) {
if !can_capture_cursor {
return;
+6 -6
View File
@@ -1,7 +1,7 @@
mod obj;
mod stl;
use std::path::PathBuf;
use std::{path::Path, str::FromStr};
use crate::{
aabb::AABB,
@@ -133,7 +133,7 @@ pub struct Object {
pub aabb: AABB,
}
pub fn load_from_file(path: &PathBuf) -> Result<Object, Box<dyn std::error::Error>> {
pub fn load_from_file(path: &Path) -> Result<Object, Box<dyn std::error::Error>> {
let path_str = match path.to_str() {
Some(s) => s,
None => return Err("Failed to convert path to string".into()),
@@ -143,10 +143,10 @@ pub fn load_from_file(path: &PathBuf) -> Result<Object, Box<dyn std::error::Erro
// TODO: if no extension, then test for binary STL magic bytes
// if no magic bytes, then try to guess based on the first line of text in the file
let obj = match SupportedFileExtensions::from_str(path.extension().unwrap().to_str().unwrap()) {
Some(SupportedFileExtensions::STL) => stl::load_stl(file)?,
Some(SupportedFileExtensions::OBJ) => obj::load_obj(path, file)?,
_ => panic!("Unsupported file extension: {}", path_str),
let obj = match SupportedFileExtensions::from_str(path.extension().unwrap().to_str().unwrap())?
{
SupportedFileExtensions::STL => stl::load_stl(file)?,
SupportedFileExtensions::OBJ => obj::load_obj(path, file)?,
};
Ok(obj)
+28 -28
View File
@@ -1,7 +1,7 @@
use std::{
collections::HashMap,
io::{BufRead, BufReader},
path::PathBuf,
path::{Path, PathBuf},
};
use log::{error, trace, warn};
@@ -29,7 +29,7 @@ enum ObjToken {
}
impl ObjToken {
fn from_str<'a>(s: &'a str) -> Option<ObjToken> {
fn from_str(s: &str) -> Option<ObjToken> {
match s {
"o" => Some(ObjToken::Object),
"g" => Some(ObjToken::Group),
@@ -113,7 +113,7 @@ fn parse_mtl(
for line in reader.lines() {
let line = line?;
// skip empty lines and comments
if line.is_empty() || line.chars().nth(0).is_some_and(|c| c == '#') {
if line.is_empty() || line.chars().next().is_some_and(|c| c == '#') {
continue;
}
@@ -174,12 +174,9 @@ fn parse_mtl(
let tex_type = TextureType::from_material_str(token).unwrap();
let name = iter.next().unwrap().to_string();
let tex = if obj_textures.contains_key(&name) {
let mut tex = obj_textures.get(&name).unwrap().clone();
tex.typ = tex_type;
tex
} else {
let tex = if let std::collections::hash_map::Entry::Vacant(e) =
obj_textures.entry(name.clone())
{
let path = path.parent().unwrap().join(&name);
let tex = match Texture::new(path, tex_type) {
Ok(v) => v,
@@ -188,8 +185,11 @@ fn parse_mtl(
continue;
}
};
obj_textures.insert(name, tex.clone());
e.insert(tex.clone());
tex
} else {
let mut tex = obj_textures.get(&name).unwrap().clone();
tex.typ = tex_type;
tex
};
@@ -218,7 +218,7 @@ fn parse_mtl(
}
pub fn load_obj(
obj_path: &PathBuf,
obj_path: &Path,
file: std::fs::File,
) -> Result<Object, Box<dyn std::error::Error>> {
let now = std::time::Instant::now();
@@ -241,7 +241,7 @@ pub fn load_obj(
for line in reader.lines() {
let line = line?;
// skip empty lines and comments
if line.is_empty() || line.chars().nth(0).is_some_and(|c| c == '#') {
if line.is_empty() || line.chars().next().is_some_and(|c| c == '#') {
continue;
}
@@ -338,9 +338,9 @@ pub fn load_obj(
let mut calculated_normal = glm::vec3(0.0, 0.0, 0.0);
if normals.is_empty() {
let part0 = face[0].split("/").next().unwrap();
let part1 = face[1].split("/").next().unwrap();
let part2 = face[2].split("/").next().unwrap();
let part0 = face[0].split('/').next().unwrap();
let part1 = face[1].split('/').next().unwrap();
let part2 = face[2].split('/').next().unwrap();
calculated_normal = glm::normalize(glm::cross(
temp_vertices[part1.parse::<i32>().unwrap() as usize - 1]
@@ -355,13 +355,13 @@ pub fn load_obj(
let mut it = vert.split("//");
let mut vert = it.next().unwrap().parse::<i32>().unwrap();
if vert < 0 {
vert = temp_vertices.len() as i32 + vert;
vert += temp_vertices.len() as i32;
} else {
vert -= 1;
}
let mut normal = it.next().unwrap().parse::<i32>().unwrap();
if normal < 0 {
normal = normals.len() as i32 + normal;
normal += normals.len() as i32;
} else {
normal -= 1;
}
@@ -370,23 +370,23 @@ pub fn load_obj(
normal: *normals.get(normal as usize).unwrap(),
tex_coords: glm::vec2(0.0, 0.0),
});
} else if vert.matches("/").count() == 2 {
let mut it = vert.split("/");
} else if vert.matches('/').count() == 2 {
let mut it = vert.split('/');
let mut vertex = it.next().unwrap().parse::<i32>().unwrap();
if vertex < 0 {
vertex = temp_vertices.len() as i32 + vertex;
vertex += temp_vertices.len() as i32;
} else {
vertex -= 1;
}
let mut t_coords = it.next().unwrap().parse::<i32>().unwrap();
if t_coords < 0 {
t_coords = tex_coords.len() as i32 + t_coords;
t_coords += tex_coords.len() as i32;
} else {
t_coords -= 1;
}
let mut normal = it.next().unwrap().parse::<i32>().unwrap();
if normal < 0 {
normal = normals.len() as i32 + normal;
normal += normals.len() as i32;
} else {
normal -= 1;
}
@@ -395,17 +395,17 @@ pub fn load_obj(
normal: *normals.get(normal as usize).unwrap(),
tex_coords: *tex_coords.get(t_coords as usize).unwrap(),
});
} else if vert.matches("/").count() == 1 {
let mut it = vert.split("/");
} else if vert.matches('/').count() == 1 {
let mut it = vert.split('/');
let mut vertex = it.next().unwrap().parse::<i32>().unwrap();
if vertex < 0 {
vertex = temp_vertices.len() as i32 + vertex;
vertex += temp_vertices.len() as i32;
} else {
vertex -= 1;
}
let mut t_coords = it.next().unwrap().parse::<i32>().unwrap();
if t_coords < 0 {
t_coords = tex_coords.len() as i32 + t_coords;
t_coords += tex_coords.len() as i32;
} else {
t_coords -= 1;
}
@@ -417,7 +417,7 @@ pub fn load_obj(
} else {
let mut vert = vert.parse::<i32>().unwrap();
if vert < 0 {
vert = temp_vertices.len() as i32 + vert;
vert += temp_vertices.len() as i32;
} else {
vert -= 1;
}
+1 -1
View File
@@ -178,7 +178,7 @@ fn parse_binary_stl(mut file: std::fs::File) -> Result<Object, Box<dyn std::erro
file.seek(std::io::SeekFrom::Start(STL_HEADER_SIZE))?;
let mut buf: [u8; 4] = [0; 4];
file.read(&mut buf)?;
file.read_exact(&mut buf)?;
let tri_count: u32 = u32::from_le_bytes(buf);
let mut min_aabb = glm::vec3(f32::MAX, f32::MAX, f32::MAX);
+1 -3
View File
@@ -17,9 +17,7 @@ fn create_named_pipe(pipe_path: PathBuf) -> UnixListener {
std::fs::remove_file(&pipe_path).expect("Failed to remove existing pipe");
}
let listener = UnixListener::bind(&pipe_path).expect("Failed to create named pipe");
listener
UnixListener::bind(&pipe_path).expect("Failed to create named pipe")
}
fn send_args_to_existing_instance(pipe_path: PathBuf, args_paths: Vec<PathBuf>) {
+1 -1
View File
@@ -43,7 +43,7 @@ impl LogMessage {
pub fn new(level: LogLevel, message: &str) -> Self {
Self {
level,
message: format!("{}", message),
message: message.to_string(),
}
}
}
+10 -15
View File
@@ -1,8 +1,8 @@
#![allow(clippy::no_effect)]
use std::env;
use std::fs::File;
use std::path::PathBuf;
use anyhow;
use glad_gl::gl;
use glfw::{Action, Context, Key, Modifiers};
use simplelog::*;
@@ -114,7 +114,7 @@ fn main() -> anyhow::Result<(), Box<dyn std::error::Error>> {
glm::vec3(0.0, 0.0, -3.0),
];
let mut delta_time: f32 = 0.0;
let mut delta_time;
let mut last_frame: f32 = 0.0;
let mut last_cursor = None;
@@ -131,8 +131,8 @@ fn main() -> anyhow::Result<(), Box<dyn std::error::Error>> {
mesh_shader.use_shader();
// set light uniforms
for i in 0..points_lights.len() {
mesh_shader.set_3fv(&format!("pointLights[{}].position", i), points_lights[i]);
for (i, point_light) in points_lights.iter().enumerate() {
mesh_shader.set_3fv(&format!("pointLights[{}].position", i), *point_light);
mesh_shader.set_float(&format!("pointLights[{}].constant", i), 1.0);
mesh_shader.set_float(&format!("pointLights[{}].linear", i), 0.09);
@@ -229,8 +229,7 @@ fn main() -> anyhow::Result<(), Box<dyn std::error::Error>> {
glfw_platform.handle_event(imgui.io_mut(), &window, &event);
}
match event {
glfw::WindowEvent::CursorPos(xpos, ypos) => {
if let glfw::WindowEvent::CursorPos(xpos, ypos) = event {
if first_mouse {
last_x = xpos as f32;
last_y = ypos as f32;
@@ -247,8 +246,7 @@ fn main() -> anyhow::Result<(), Box<dyn std::error::Error>> {
{
if window.get_key(glfw::Key::LeftShift) == Action::Press {
state.camera.move_camera(-xoffset, -yoffset);
} else {
if let Some(active_model) = state.active_model {
} else if let Some(active_model) = state.active_model {
let x_rotation =
xoffset * state.camera.sensitivity * state.rotation_speed;
let y_rotation =
@@ -264,9 +262,6 @@ fn main() -> anyhow::Result<(), Box<dyn std::error::Error>> {
}
}
}
_ => {}
}
}
//
// draw scene to framebuffer
@@ -344,8 +339,8 @@ fn main() -> anyhow::Result<(), Box<dyn std::error::Error>> {
fn draw_grid(shader: &threedobs::shader::Shader, view_mat: &glm::Mat4, projection_mat: &glm::Mat4) {
shader.use_shader();
shader.set_mat4fv("view", &view_mat);
shader.set_mat4fv("projection", &projection_mat);
shader.set_mat4fv("view", view_mat);
shader.set_mat4fv("projection", projection_mat);
unsafe {
gl::DrawArrays(gl::TRIANGLES, 0, 6);
}
@@ -408,7 +403,7 @@ fn create_scene_framebuffer() -> u32 {
gl::BindFramebuffer(gl::FRAMEBUFFER, fb);
}
return fb;
fb
}
fn create_scene_texture_and_renderbuffer(window: &glfw::Window, fbo: u32) -> (u32, u32) {
@@ -461,5 +456,5 @@ fn create_scene_texture_and_renderbuffer(window: &glfw::Window, fbo: u32) -> (u3
}
}
return (fb_texture, rbo);
(fb_texture, rbo)
}
+5 -8
View File
@@ -1,5 +1,4 @@
use glad_gl::gl;
use log::warn;
use crate::{
importer::{Material, TextureType},
@@ -20,15 +19,13 @@ fn create_rotation_matrix(pitch: f32, yaw: f32, roll: f32, pivot: glm::Vec3) ->
let trans_to_origin = glm::ext::translate(&mat, -glm::vec3(pivot.x, pivot.y, pivot.z));
let trans_back_to_center = glm::ext::translate(&mat, glm::vec3(pivot.x, pivot.y, pivot.z));
let combined = trans_back_to_center * rot_z * rot_y * rot_x * trans_to_origin;
combined
trans_back_to_center * rot_z * rot_y * rot_x * trans_to_origin
}
pub fn apply_rotation(matrix: &glm::Mat4, rot: glm::Vec3, pivot: glm::Vec3) -> glm::Mat4 {
let rot = create_rotation_matrix(rot.x, rot.y, rot.z, pivot);
return rot * *matrix;
rot * *matrix
}
#[derive(Debug)]
@@ -69,7 +66,7 @@ impl Mesh {
gl::BufferData(
gl::ARRAY_BUFFER,
(std::mem::size_of::<Vertex>() * vertices.len() as usize) as isize,
(std::mem::size_of::<Vertex>() * vertices.len()) as isize,
vertices.as_ptr() as *const std::ffi::c_void,
gl::STATIC_DRAW,
);
@@ -77,7 +74,7 @@ impl Mesh {
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo);
gl::BufferData(
gl::ELEMENT_ARRAY_BUFFER,
(std::mem::size_of::<u32>() * indices.len() as usize) as isize,
(std::mem::size_of::<u32>() * indices.len()) as isize,
indices.as_ptr() as *const std::ffi::c_void,
gl::STATIC_DRAW,
);
@@ -183,7 +180,7 @@ impl Mesh {
}
if show_textures {
shader.set_bool("useTextures", self.material.textures.len() > 0);
shader.set_bool("useTextures", !self.material.textures.is_empty());
for (i, tex) in self.material.textures.iter().enumerate() {
shader.set_bool("hasEmissionTexture", false);
unsafe {
+2 -2
View File
@@ -49,7 +49,7 @@ impl Model {
model.set_mem_usage();
return model;
model
}
pub fn draw(&self, shader: &Shader, draw_aabb: bool, show_textures: bool) {
@@ -109,7 +109,7 @@ impl Model {
size += std::mem::size_of::<importer::Material>();
for texture in &mesh.material.textures {
size += std::mem::size_of_val(&texture);
size += std::mem::size_of_val(texture);
}
for vertex in &mesh.vertices {
size += std::mem::size_of_val(vertex);
+12 -12
View File
@@ -52,7 +52,7 @@ impl Default for State {
fov_zoom: true,
rotation_speed: 1.0,
wireframe: false,
camera: Camera::new(),
camera: Camera::default(),
objects: vec![],
viewport_size: [0.0, 0.0],
logger: logger::WritableLog::default(),
@@ -70,7 +70,7 @@ impl State {
id = last_model.id + 1;
}
return id;
id
}
}
@@ -95,7 +95,7 @@ pub fn init_imgui(
let mut glfw_platform = imgui_glfw_support::GlfwPlatform::init(&mut imgui);
glfw_platform.attach_window(
imgui.io_mut(),
&window,
window,
imgui_glfw_support::HiDpiMode::Default,
);
@@ -114,7 +114,7 @@ pub fn init_imgui(
gl::load(|e| window.get_proc_address(e) as *const std::os::raw::c_void);
let renderer = imgui_opengl_renderer::Renderer::new(&mut imgui);
glfw_platform.set_clipboard_backend(&mut imgui, &window);
glfw_platform.set_clipboard_backend(&mut imgui, window);
(imgui, glfw_platform, renderer)
}
@@ -186,14 +186,14 @@ pub fn draw_main_menu_bar(ui: &imgui::Ui, state: &mut State, window: &mut glfw::
let mem = state
.objects
.iter()
.fold(0 as usize, |acc, m| acc + m.mem_usage) as f32;
.fold(0_usize, |acc, m| acc + m.mem_usage) as f32;
let mem_fps = format!(
"Mem: {:.1}MB | FPS: {:.1}",
mem / (1024.0 * 1024.0),
state.fps
);
let avail_size = [
*ui.content_region_avail().get(0).unwrap() - ui.calc_text_size(&mem_fps)[0],
*ui.content_region_avail().first().unwrap() - ui.calc_text_size(&mem_fps)[0],
0.0,
];
ui.dummy(avail_size);
@@ -223,7 +223,7 @@ fn draw_about_window(ui: &imgui::Ui, state: &mut State) {
env!("CARGO_PKG_VERSION"),
env!("GIT_HASH")
));
ui.text(format!("{}", env!("CARGO_PKG_DESCRIPTION")));
ui.text(env!("CARGO_PKG_DESCRIPTION"));
ui.spacing();
ui.spacing();
ui.text(format!("Made by: {}", env!("CARGO_PKG_AUTHORS")));
@@ -379,7 +379,7 @@ fn draw_object_hierarchy(ui: &imgui::Ui, state: &mut State, idx: usize) -> bool
return true;
}
return false;
false
}
fn draw_objects_window(ui: &imgui::Ui, state: &mut State) {
@@ -420,7 +420,7 @@ fn draw_objects_window(ui: &imgui::Ui, state: &mut State) {
state.objects.remove(i);
if state.active_model == Some(selected_obj_id) {
let model = state.objects.last_mut().map(|m| m.reset_rotation());
state.active_model = model.and_then(|o| Some(o.id));
state.active_model = model.map(|o| o.id);
state
.camera
.focus_on_selected_model(state.active_model, &state.objects);
@@ -428,7 +428,7 @@ fn draw_objects_window(ui: &imgui::Ui, state: &mut State) {
continue;
}
i = i + 1;
i += 1;
}
}
});
@@ -548,7 +548,7 @@ fn draw_viewport(ui: &imgui::Ui, state: &mut State, texture: u32) {
0,
gl::RGBA,
gl::UNSIGNED_BYTE,
(w * h * 4) as i32,
w * h * 4,
pixels.as_mut_ptr() as *mut std::ffi::c_void,
);
}
@@ -648,7 +648,7 @@ pub fn draw_ui(
let cursor = ui.mouse_cursor();
if *last_cursor != cursor {
*last_cursor = cursor;
glfw_platform.prepare_render(&ui, window);
glfw_platform.prepare_render(ui, window);
}
}
+9 -6
View File
@@ -1,4 +1,5 @@
use std::path::PathBuf;
use std::str::FromStr;
use ::log::{error, info};
use anyhow::{Context, Result};
@@ -12,12 +13,14 @@ pub enum SupportedFileExtensions {
STL,
}
impl SupportedFileExtensions {
pub fn from_str(s: &str) -> Option<Self> {
impl std::str::FromStr for SupportedFileExtensions {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"obj" => Some(Self::OBJ),
"stl" => Some(Self::STL),
_ => None,
"obj" => Ok(Self::OBJ),
"stl" => Ok(Self::STL),
_ => Err(format!("Unsupported file extension: {}", s)),
}
}
}
@@ -91,7 +94,7 @@ pub fn import_models_from_paths(paths: &Vec<PathBuf>, state: &mut ui::ui::State)
}
match model_path.extension() {
Some(ext) => {
if SupportedFileExtensions::from_str(ext.to_str().unwrap()).is_none() {
if SupportedFileExtensions::from_str(ext.to_str().unwrap()).is_err() {
info!(
"Skipping file \"{}\" because it is not an OBJ or STL file",
filename.unwrap().to_str().unwrap()