Selaa lähdekoodia

update everything

deltanedas 4 viikkoa sitten
vanhempi
sitoutus
8617b64610

+ 7 - 6
Cargo.toml

@@ -1,10 +1,11 @@
 [package]
 name = "chair"
-version = "0.4.0"
-edition = "2021"
+version = "0.5.0"
+edition = "2024"
+rust-version = "1.85"
 description = "An efficient binary mesh format which is both small and extremely fast to read."
 readme = "README.md"
-repository = "https://gitgud.io/deltanedas/chair"
+repository = "https://git.goida.zip/deltanedas/chair"
 license = "GPL-3.0-or-later"
 categories = ["graphics"]
 keywords = ["mesh"]
@@ -12,10 +13,10 @@ keywords = ["mesh"]
 [dependencies]
 bytemuck = {version = "1", features = ["derive"]}
 byteorder = {version = "1", optional = true}
-enumflags2 = "0.7.8"
+enumflags2 = "0.7.12"
 log = {version = "0.4", optional = true}
-thiserror = {version = "1", optional = true}
-wgpu = {version = "0.19", optional = true}
+thiserror = {version = "2", optional = true}
+wgpu = {version = "30", optional = true}
 
 [features]
 default = ["io", "mesh", "vertex-impls"]

+ 2 - 0
README.md

@@ -6,6 +6,8 @@ Textures are supported by loading them from an atlas and mapping mesh uvs to the
 
 Comes with wgpu integration, if using bevy see the `[bevy_chair](https://lib.rs/bevy_chair)` loader plugin.
 
+MSRV is 1.85.0
+
 # loading and drawing meshes with wgpu
 
 ```rs

+ 3 - 3
examples/reader/Cargo.toml

@@ -1,8 +1,8 @@
 [package]
 name = "reader"
-version = "0.1.1"
-edition = "2021"
+version = "0.5.0"
+edition = "2024"
 
 [dependencies]
 chair = {path = "../..", default-features = false, features = ["io", "vertex-impls"]}
-env_logger = "0.9"
+env_logger = "0.11"

+ 5 - 5
examples/viewer/Cargo.toml

@@ -1,7 +1,7 @@
 [package]
 name = "viewer"
-version = "0.4.0"
-edition = "2021"
+version = "0.5.0"
+edition = "2024"
 
 [dependencies]
 bytemuck = {version = "1", features = ["derive"]}
@@ -9,9 +9,9 @@ cgmath = "0.18"
 chair = {path = "../.."}
 env_logger = "0.11"
 image = {version = "0.25", default-features = false, features = ["png"]}
-pollster = "0.2"
-wgpu = "0.19"
-winit = "0.29"
+pollster = "1"
+wgpu = "30"
+winit = "0.30"
 
 [profile.release]
 strip = true

+ 72 - 56
examples/viewer/src/main.rs

@@ -4,76 +4,92 @@ use crate::render::*;
 
 // future.block_on()
 use pollster::FutureExt as _;
-use wgpu::SurfaceError;
 use winit::{
+	application::ApplicationHandler,
 	dpi::PhysicalSize,
 	event::*,
-	event_loop::EventLoop,
+	event_loop::{ActiveEventLoop, EventLoop},
 	keyboard::{Key, NamedKey},
-	window::WindowBuilder
+	window::{Window, WindowId}
 };
 
-fn main() {
-	env_logger::init();
+struct App {
+	mesh_path: String,
+	renderer: Option<Renderer>
+}
 
-	let path = std::env::args().nth(1)
-		.expect("Run with a mesh file");
+impl ApplicationHandler for App {
+	fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+		let attrs = Window::default_attributes()
+			.with_title("chair model viewer")
+			.with_inner_size(PhysicalSize::new(1280, 720));
 
-	let event_loop = EventLoop::new()
-		.expect("Failed to create event loop");
+		let window = event_loop.create_window(attrs)
+			.expect("failed to create window");
+		self.renderer = Some(Renderer::new(window, &self.mesh_path).block_on());
+	}
 
-	let window = WindowBuilder::new()
-		.with_title("chair model viewer")
-		.with_inner_size(PhysicalSize::new(1280, 720))
-		.build(&event_loop)
-		.unwrap();
-	let id = window.id();
-
-	let mut renderer = Renderer::new(&window, &path).block_on();
-
-	event_loop.run(move |event, elwt| match event {
-		Event::WindowEvent {
-			ref event,
-			window_id
-		} if window_id == id => {
-			match event {
-				// Exit when window is closed or ESC is pressed
-				WindowEvent::CloseRequested
-				| WindowEvent::KeyboardInput {
-					event: KeyEvent {
-						state: ElementState::Pressed,
-						logical_key: Key::Named(NamedKey::Escape),
-						..
-					},
-					..
-				} => elwt.exit(),
+	fn window_event(
+		&mut self,
+		event_loop: &ActiveEventLoop,
+		window_id: WindowId,
+		event: WindowEvent)
+	{
+		let Some(renderer) = &mut self.renderer else {
+			return;
+		};
+
+		if window_id != renderer.window_id() {
+			return;
+		}
 
-				// Handle window resizing
-				WindowEvent::Resized(size) => renderer.resize(*size),
+		match event {
+			// Exit when window is closed or ESC is pressed
+			WindowEvent::CloseRequested
+			| WindowEvent::KeyboardInput {
+				event: KeyEvent {
+					state: ElementState::Pressed,
+					logical_key: Key::Named(NamedKey::Escape),
+					..
+				},
+				..
+			} => event_loop.exit(),
 
-				// Handle user input
-				WindowEvent::CursorMoved {position, ..} => {
-					renderer.cursor_moved(position.x, position.y);
-				}
+			// Handle window resizing
+			WindowEvent::Resized(size) => renderer.resize(size),
 
-				_ => {}
-			}
-		}
+			// Handle user input
+			WindowEvent::CursorMoved {position, ..} => {
+				renderer.cursor_moved(position.x, position.y);
+			},
 
-		// Handle drawing
-		Event::AboutToWait => match renderer.render() {
-			Ok(_) => {},
-			// Reconfigure the surface if lost
-			Err(SurfaceError::Lost) => renderer.recreate(),
-			// death
-			Err(SurfaceError::OutOfMemory) => {
-				eprintln!("Out of memory!");
-				elwt.exit();
+			// Handle drawing
+			WindowEvent::RedrawRequested => {
+				renderer.render();
 			},
-			// All other errors should be temporary
-			Err(e) => eprintln!("{:?}", e)
+
+			_ => {}
 		}
+	}
+
+	fn suspended(&mut self, _: &ActiveEventLoop) {
+		self.renderer = None;
+	}
+}
+
+fn main() {
+	env_logger::init();
+
+	let mesh_path = std::env::args().nth(1)
+		.expect("Run with a mesh file");
+
+	let event_loop = EventLoop::new()
+		.expect("Failed to create event loop");
 
-		_ => {}
-	}).expect("Failed to run event loop");
+	let mut app = App {
+		mesh_path,
+		renderer: None
+	};
+	event_loop.run_app(&mut app)
+		.expect("Failed to run event loop");
 }

+ 3 - 3
examples/viewer/src/render/atlas.rs

@@ -48,14 +48,14 @@ pub fn load_texture(device: &Device, queue: &Queue, bytes: &[u8]) -> (BindGroup,
 
 	// copy texture from host to device memory
 	queue.write_texture(
-		ImageCopyTexture {
+		TexelCopyTextureInfo {
 			texture: &texture,
 			mip_level: 0,
 			origin: Origin3d::ZERO,
 			aspect: TextureAspect::All
 		},
 		&pixels,
-		ImageDataLayout {
+		TexelCopyBufferLayout {
 			offset: 0,
 			// 4 BPP
 			bytes_per_row: Some(4 * dimensions.0),
@@ -71,7 +71,7 @@ pub fn load_texture(device: &Device, queue: &Queue, bytes: &[u8]) -> (BindGroup,
 		address_mode_w: AddressMode::ClampToEdge,
 		mag_filter: FilterMode::Linear,
 		min_filter: FilterMode::Nearest,
-		mipmap_filter: FilterMode::Nearest,
+		mipmap_filter: MipmapFilterMode::Nearest,
 		..Default::default()
 	});
 

+ 19 - 11
examples/viewer/src/render/pipeline.rs

@@ -6,34 +6,41 @@ use crate::render::{
 use chair::{TexturedVertex, Vertex};
 use wgpu::*;
 
-pub fn mesh(device: &Device, config: &SurfaceConfiguration, bind_layouts: &[&BindGroupLayout]) -> RenderPipeline {
+pub fn mesh(device: &Device, config: &SurfaceConfiguration, bind_layouts: &[Option<&BindGroupLayout>]) -> RenderPipeline {
 	let module = device.create_shader_module(include_wgsl!("../../shaders/mesh.wgsl"));
 
 	let layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
 		label: Some("Mesh Pipeline Layout"),
 		bind_group_layouts: bind_layouts,
-		push_constant_ranges: &[]
+		immediate_size: 0
 	});
 
+	let compilation_options = PipelineCompilationOptions {
+		constants: Default::default(),
+		zero_initialize_workgroup_memory: false
+	};
+
 	device.create_render_pipeline(&RenderPipelineDescriptor {
 		label: Some("Mesh Pipeline"),
 		layout: Some(&layout),
 		vertex: VertexState {
 			module: &module,
-			entry_point: "vs_main",
+			entry_point: Some("vs_main"),
 			buffers: &[
-				TexturedVertex::layout(),
-				ObjectData::layout()
-			]
+				Some(TexturedVertex::layout()),
+				Some(ObjectData::layout())
+			],
+			compilation_options: compilation_options.clone()
 		},
 		fragment: Some(FragmentState {
 			module: &module,
-			entry_point: "fs_main",
+			entry_point: Some("fs_main"),
 			targets: &[Some(ColorTargetState {
 				format: config.format,
 				blend: Some(BlendState::REPLACE),
 				write_mask: ColorWrites::ALL
-			})]
+			})],
+			compilation_options
 		}),
 		primitive: PrimitiveState {
 			topology: PrimitiveTopology::TriangleList,
@@ -46,9 +53,9 @@ pub fn mesh(device: &Device, config: &SurfaceConfiguration, bind_layouts: &[&Bin
 		},
 		depth_stencil: Some(DepthStencilState {
 			format: DepthBuffer::FORMAT,
-			depth_write_enabled: true,
+			depth_write_enabled: Some(true),
 			// this does the actual depth testing
-			depth_compare: CompareFunction::Less,
+			depth_compare: Some(CompareFunction::Less),
 			stencil: Default::default(),
 			bias: Default::default()
 		}),
@@ -57,6 +64,7 @@ pub fn mesh(device: &Device, config: &SurfaceConfiguration, bind_layouts: &[&Bin
 			mask: !0,
 			alpha_to_coverage_enabled: false
 		},
-		multiview: None
+		cache: None,
+		multiview_mask: None
 	})
 }

+ 44 - 21
examples/viewer/src/render/renderer.rs

@@ -9,7 +9,8 @@ use crate::render::{
 use std::{
 	f64::consts::*,
 	fs,
-	iter
+	iter,
+	sync::Arc
 };
 
 use bytemuck::cast_slice;
@@ -20,14 +21,15 @@ use wgpu::{
 };
 use winit::{
 	dpi::*,
-	window::{CursorGrabMode, Window}
+	window::{CursorGrabMode, Window, WindowId}
 };
 
 pub type WindowSize = PhysicalSize<u32>;
 pub type MousePos = PhysicalPosition<f64>;
 
-pub struct Renderer<'w> {
-	surface: Surface<'w>,
+pub struct Renderer {
+	window: Arc<Window>,
+	surface: Surface<'static>,
 	device: Device,
 	queue: Queue,
 	config: SurfaceConfiguration,
@@ -48,12 +50,13 @@ pub struct Renderer<'w> {
 	mesh_instances: Buffer
 }
 
-impl<'w> Renderer<'w> {
-	pub async fn new(window: &'w Window, path: &str) -> Self {
+impl Renderer {
+	pub async fn new(window: Window, path: &str) -> Self {
 		let size = window.inner_size();
 
-		let instance = Instance::new(InstanceDescriptor::default());
-		let surface = instance.create_surface(window)
+		let window = Arc::new(window);
+		let instance = Instance::new(InstanceDescriptor::new_without_display_handle());
+		let surface = instance.create_surface(window.clone())
 			.expect("Failed to create surface");
 		let adapter = instance.request_adapter(
 			// want to find the fastest gpu first, must support rendering to our surface
@@ -62,17 +65,17 @@ impl<'w> Renderer<'w> {
 				compatible_surface: Some(&surface),
 				// no software rendering please
 				force_fallback_adapter: false,
+				apply_limit_buckets: false // don't care about fingerprinting
 			}
 		).await.expect("Failed to find a suitable gpu");
 
 		let (device, queue) = adapter.request_device(
 			// don't care about what the gpu supports
 			&DeviceDescriptor {
-				label: None,
 				required_features: Features::empty(),
-				required_limits: Limits::default()
-			},
-			None // Trace path
+				required_limits: Limits::default(),
+				..Default::default()
+			}
 		).await.expect("Failed to find a suitable physical device");
 
 		let caps = surface.get_capabilities(&adapter);
@@ -83,6 +86,7 @@ impl<'w> Renderer<'w> {
 			// using the surface to write to the window
 			usage: TextureUsages::RENDER_ATTACHMENT,
 			format,
+			color_space: SurfaceColorSpace::Auto,
 			width: size.width,
 			height: size.height,
 			present_mode: PresentMode::AutoVsync,
@@ -138,8 +142,8 @@ impl<'w> Renderer<'w> {
 
 		// create mesh pipeline
 		let mesh_pipeline = pipeline::mesh(&device, &config, &[
-			&texture_layout,
-			&camera_layout
+			Some(&texture_layout),
+			Some(&camera_layout)
 		]);
 
 		// TODO: move elsewhere
@@ -148,6 +152,7 @@ impl<'w> Renderer<'w> {
 //		window.set_cursor_visible(false);
 
 		Self {
+			window,
 			surface,
 			device,
 			queue,
@@ -168,6 +173,10 @@ impl<'w> Renderer<'w> {
 		}
 	}
 
+	pub fn window_id(&self) -> WindowId {
+		self.window.id()
+	}
+
 	pub fn resize(&mut self, size: WindowSize) {
 		self.size = size;
 		self.config.width = size.width;
@@ -197,8 +206,23 @@ impl<'w> Renderer<'w> {
 		self.queue.write_buffer(&self.uniforms, 0, bytes);
 	}
 
-	pub fn render(&mut self) -> Result<(), SurfaceError> {
-		let output = self.surface.get_current_texture()?;
+	pub fn render(&mut self) {
+		self.window.request_redraw();
+
+		let output = match self.surface.get_current_texture() {
+			CurrentSurfaceTexture::Success(output) => output,
+			CurrentSurfaceTexture::Suboptimal(_) | CurrentSurfaceTexture::Outdated => {
+				self.recreate();
+				return; // try again next frame
+			},
+			CurrentSurfaceTexture::Lost => {
+				panic!("Surface lost!");
+			},
+			_ => {
+				// probably temporary errors
+				return;
+			}
+		};
 		let view = output.texture.create_view(&TextureViewDescriptor::default());
 		let mut encoder = self.device.create_command_encoder(&CommandEncoderDescriptor {
 			label: Some("Render Encoder")
@@ -208,9 +232,7 @@ impl<'w> Renderer<'w> {
 
 		// submit commands for rendering
 		self.queue.submit(iter::once(encoder.finish()));
-		output.present();
-
-		Ok(())
+		self.queue.present(output);
 	}
 
 	pub fn center(&self) -> MousePos {
@@ -224,6 +246,8 @@ impl<'w> Renderer<'w> {
 				view,
 				// no multisampling
 				resolve_target: None,
+				// 2D
+				depth_slice: None,
 				ops: Operations {
 					// clear with this colour
 					load: LoadOp::Clear(Color {
@@ -245,8 +269,7 @@ impl<'w> Renderer<'w> {
 				}),
 				stencil_ops: None
 			}),
-			timestamp_writes: None,
-			occlusion_query_set: None
+			..Default::default()
 		});
 
 		pass.set_pipeline(&self.mesh_pipeline);

+ 2 - 2
src/io.rs

@@ -244,7 +244,7 @@ impl<'a, A: Atlas> MeshReader<'a, A> {
 
 				let region = if features.contains(MeshFeature::Textured) {
 					textures.get(bytes.read_u8()? as usize)
-						.ok_or_else(|| Error::UnknownTexture(n))?
+						.ok_or(Error::UnknownTexture(n))?
 				} else {
 					&AtlasRegion {
 						xy: [0.0; 2],
@@ -263,7 +263,7 @@ impl<'a, A: Atlas> MeshReader<'a, A> {
 					let col = if features.contains(MeshFeature::Coloured) {
 						let index = read_col_index(bytes)?;
 						colours.get(index as usize).copied()
-							.ok_or_else(|| Error::UnknownColour(index))?
+							.ok_or(Error::UnknownColour(index))?
 					} else {
 						[1.0; 4]
 					};

+ 1 - 1
src/vertex.rs

@@ -17,6 +17,7 @@ use wgpu::*;
 pub type Index = u32;
 
 /// The vertex trait implemented by vertex types
+///
 /// # Example
 /// ```
 /// # use bytemuck::{Pod, Zeroable};
@@ -48,7 +49,6 @@ pub type Index = u32;
 /// 	}
 /// }
 /// ```
-
 pub trait Vertex: Pod + Zeroable {
 	/// Create a new vertex, using at least position
 	fn new(pos: [f32; 3], col: [f32; 4], normals: [f32; 3], uvs: [f32; 2]) -> Self;