Selaa lähdekoodia

uvs working + viewer example

zenith 4 vuotta sitten
vanhempi
sitoutus
4fb25f42a9

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "chair"
-version = "0.1.0"
+version = "0.1.1"
 edition = "2021"
 description = "An efficient binary mesh format which is both small and extremely fast to read."
 readme = "README.md"

+ 2 - 0
build.rs

@@ -7,6 +7,8 @@ use std::{
 };
 
 fn main() -> Result<()> {
+	println!("cargo:rerun-if-changed=build.rs");
+
 	let mut path = PathBuf::from(var("OUT_DIR")
 		.expect("Cargo didn't set OUT_DIR"));
 	path.push("normals.rs");

BIN
chair.blend


BIN
chair.chr


+ 42 - 20
chair_exporter.py

@@ -7,7 +7,7 @@ bl_info = {
 	"blender": (3, 0, 0),
 	"location": "File > Import-Export > Chair Mesh (.chr)",
 	# Same as the crate version
-	"version": (0.1, 0),
+	"version": (0, 1, 1),
 	"category": "Import-Export"
 }
 
@@ -17,28 +17,24 @@ import math
 import struct
 
 def face_to_tris(face, mesh, matrix, vertices, vertex_ids, indices):
-	i = len(vertices)
-	for verti in face.vertices:
+	uvs = mesh.uv_layers.active.data
+	for n in range(3):
+		verti = face.vertices[n]
+		loopi = face.loops[n]
 		vert = mesh.vertices[verti]
-		v = [(matrix @ vert.co)[:], (vert.normal)[:]]
+		loop = mesh.loops[loopi]
+		v = [(matrix @ vert.co)[:], (loop.normal)[:], (uvs[loopi].uv)[:]]
+		# really inefficient but this is pyton so
 		key = str(v)
 		if key in vertex_ids:
 			i = vertex_ids[key]
 		else:
 			# new vertex, push to list
+			i = len(vertices)
 			vertices.append(v)
 			vertex_ids[key] = i
 
-	# TODO: general form for n-gons
-	# Single triangle
-	indices.append(i)
-	indices.append(i + 1)
-	indices.append(i + 2)
-	if len(face.vertices) == 4:
-		# Second triangle of quad
 		indices.append(i)
-		indices.append(i + 2)
-		indices.append(i + 3)
 
 def process_scene(context, apply_modifiers):
 	objects = []
@@ -100,6 +96,26 @@ def index_size(vertices):
 		return 2
 	return 4
 
+def write_vec2_float(f, v):
+	f.write(bytes(struct.pack("<f", v[0])))
+	f.write(bytes(struct.pack("<f", 1.0 - v[1])))
+
+def write_vec2_byte(f, v):
+	x = v[0]
+	y = v[1]
+	while x < 0.0:
+		x += 1.0
+	while y < 0.0:
+		y += 1.0
+	while x > 1.0:
+		x -= 1.0
+	while y > 1.0:
+		y -= 1.0
+	x = int(x * 128)
+	# flip y axis
+	y = 128 - int(y * 128)
+	f.write(bytes([x, y]))
+
 def write_vec3_float(f, v):
 	# <f = little-endian float
 	f.write(bytes(struct.pack("<f", v[0])))
@@ -113,7 +129,6 @@ def write_vec3_byte(f, v, scale, offset):
 	# Y = up in chair/wgpu, Z = up in blender so swap them
 	y = 128 * (v[2] - offset[2]) / scale[2]
 	z = 128 * (v[1] - offset[1]) / scale[1]
-	print("writing float " + str(x) + ", " + str(y) + ", " + str(z))
 	f.write(bytes([int(x), int(y), int(z)]))
 
 def index_normal(n):
@@ -162,7 +177,7 @@ def write_model(path, objects, indices, export_colours, export_normals, export_u
 	# TODO: export texture names
 	if export_uvs:
 		f.write(bytes([1, 5]))
-		f.write(bytes("error", "ascii"))
+		f.write(bytes("chair", "ascii"))
 
 	# TODO: export skeleton
 
@@ -170,6 +185,7 @@ def write_model(path, objects, indices, export_colours, export_normals, export_u
 	for obj in objects:
 		# Vertices count for this object
 		f.write(len(obj[0]).to_bytes(4, "little"))
+
 		scale = obj[1]
 		offset = obj[2]
 		if short_pos:
@@ -184,6 +200,14 @@ def write_model(path, objects, indices, export_colours, export_normals, export_u
 		else:
 			write_normals = write_vec3_float
 
+		if export_uvs:
+			# TODO: actual texture index
+			f.write(bytes([0]))
+		if short_uvs:
+			write_uvs = write_vec2_byte
+		else:
+			write_uvs = write_vec2_float
+
 		# TODO: texture name index
 
 		# Write data
@@ -195,9 +219,7 @@ def write_model(path, objects, indices, export_colours, export_normals, export_u
 			if export_normals:
 				write_normals(f, v[1])
 			if export_uvs:
-				# TODO uvs, short uvs
-				f.write(struct.pack("<f", 0))
-				f.write(struct.pack("<f", 0))
+				write_uvs(f, v[2])
 			# TODO: bone weights
 
 	# Indices
@@ -234,7 +256,7 @@ class ModelExporter(Operator, ExportHelper):
 	export_colours: BoolProperty(
 		name = "Export Colours",
 		description = "Save vertex colours in the exported mesh",
-		default = True
+		default = False
 	)
 
 	export_normals: BoolProperty(
@@ -246,7 +268,7 @@ class ModelExporter(Operator, ExportHelper):
 	export_uvs: BoolProperty(
 		name = "Export UVs",
 		description = "Save vertex texture coordinates (and texture names) in the exported mesh",
-		default = False
+		default = True
 	)
 
 	export_skeleton: BoolProperty(

+ 1 - 1
examples/reader/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "reader"
-version = "0.1.0"
+version = "0.1.1"
 edition = "2021"
 
 [dependencies]

+ 2 - 0
examples/viewer/.gitignore

@@ -0,0 +1,2 @@
+/target
+/Cargo.lock

+ 14 - 0
examples/viewer/Cargo.toml

@@ -0,0 +1,14 @@
+[package]
+name = "viewer"
+version = "0.1.1"
+edition = "2021"
+
+[dependencies]
+bytemuck = {version = "1", features = ["derive"]}
+cgmath = "0.18"
+chair = {path = "../.."}
+env_logger = "0.9"
+image = {version = "0.24", default-features = false, features = ["png"]}
+pollster = "0.2"
+wgpu = "0.14"
+winit = "0.27"

+ 56 - 0
examples/viewer/shaders/mesh.wgsl

@@ -0,0 +1,56 @@
+struct VertexInput {
+	@location(0) pos: vec3<f32>,
+	@location(1) uvs: vec2<f32>
+};
+
+struct VertexOutput {
+	@builtin(position) clip_position: vec4<f32>,
+	@location(0) uvs: vec2<f32>,
+	@location(1) col: vec4<f32>
+	// TODO: use normals for lighting somehow
+};
+
+struct Instance {
+	@location(2) model0: vec4<f32>,
+	@location(3) model1: vec4<f32>,
+	@location(4) model2: vec4<f32>,
+	@location(5) model3: vec4<f32>,
+	@location(6) col: vec4<f32>
+};
+
+// Vertex shader
+
+struct Uniforms {
+	view_proj: mat4x4<f32>
+};
+@group(1)
+@binding(0)
+var<uniform> u: Uniforms;
+
+@vertex
+fn vs_main(
+	in: VertexInput,
+	obj: Instance
+) -> VertexOutput {
+	let model = mat4x4<f32>(obj.model0, obj.model1, obj.model2, obj.model3);
+
+	var out: VertexOutput;
+	out.clip_position = u.view_proj * model * vec4<f32>(in.pos, 1.0);
+	out.uvs = in.uvs;
+	out.col = obj.col;
+	return out;
+}
+
+// Fragment shader
+
+@group(0)
+@binding(0)
+var t_diffuse: texture_2d<f32>;
+@group(0)
+@binding(1)
+var s_diffuse: sampler;
+
+@fragment
+fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
+	return textureSample(t_diffuse, s_diffuse, in.uvs) * in.col;
+}

+ 93 - 0
examples/viewer/src/main.rs

@@ -0,0 +1,93 @@
+mod render;
+
+use crate::render::*;
+
+use std::time::Instant;
+
+// future.block_on()
+use pollster::FutureExt as _;
+use wgpu::SurfaceError;
+use winit::{
+	dpi::PhysicalSize,
+	event::*,
+	event_loop::{ControlFlow, EventLoop},
+	window::WindowBuilder
+};
+
+fn main() {
+	env_logger::init();
+
+	let path = std::env::args().nth(1)
+		.expect("Run with a mesh file");
+
+	let event_loop = EventLoop::new();
+	let window = WindowBuilder::new()
+		.with_title("chair model viewer")
+		.with_inner_size(PhysicalSize::new(1280, 720))
+		// TODO: center on display
+		.build(&event_loop)
+		.unwrap();
+
+	let mut renderer = Renderer::new(&window, &path).block_on();
+
+	event_loop.run(move |event, _, control_flow| match event {
+		Event::WindowEvent {
+			ref event,
+			window_id
+		} if window_id == window.id() => {
+			match event {
+				// Exit when window is closed or ESC is pressed
+				WindowEvent::CloseRequested
+				| WindowEvent::KeyboardInput {
+					input: KeyboardInput {
+						state: ElementState::Pressed,
+						virtual_keycode: Some(VirtualKeyCode::Escape),
+						..
+					},
+					..
+				} => *control_flow = ControlFlow::Exit,
+
+				// Handle window resizing
+				WindowEvent::Resized(size) => {
+					renderer.resize(*size);
+				},
+				WindowEvent::ScaleFactorChanged {new_inner_size, ..} => {
+					renderer.resize(**new_inner_size);
+				},
+
+				// Handle user input
+				WindowEvent::CursorMoved {position, ..} => {
+					renderer.cursor_moved(position.x, position.y);
+				}
+
+				_ => {}
+			}
+		},
+
+		// Handle drawing
+		Event::RedrawRequested(window_id) if window_id == window.id() => {
+			let start = Instant::now();
+			match renderer.render() {
+				Ok(_) => {},
+				// Reconfigure the surface if lost
+				Err(SurfaceError::Lost) => renderer.recreate(),
+				// death
+				Err(SurfaceError::OutOfMemory) => {
+					eprintln!("Out of memory!");
+					*control_flow = ControlFlow::Exit;
+				},
+				// All other errors should be temporary
+				Err(e) => eprintln!("{:?}", e)
+			}
+
+			let frametime = start.elapsed().as_micros();
+			// TODO: display
+		},
+		Event::MainEventsCleared => {
+			// RedrawRequested will only trigger once, unless manually requested
+			window.request_redraw();
+		},
+
+		_ => {}
+	});
+}

+ 9 - 0
examples/viewer/src/render.rs

@@ -0,0 +1,9 @@
+mod atlas;
+mod camera;
+mod depth;
+mod object;
+mod pipeline;
+mod renderer;
+mod vertex;
+
+pub use renderer::Renderer;

+ 119 - 0
examples/viewer/src/render/atlas.rs

@@ -0,0 +1,119 @@
+use std::num::NonZeroU32;
+
+use chair::*;
+use wgpu::*;
+
+pub struct WholeAtlas;
+
+impl Atlas for WholeAtlas {
+	fn get(&self, _: &str) -> Option<&AtlasRegion> {
+		// use whole texture 0.0 to 1.0
+		Some(&AtlasRegion {
+			xy: [0.0; 2],
+			x2y: [1.0, 0.0],
+			x2y2: [1.0; 2],
+			xy2: [0.0, 1.0]
+		})
+	}
+}
+
+// load a texture from an image in memory
+pub fn load_texture(device: &Device, queue: &Queue, bytes: &[u8]) -> (BindGroup, BindGroupLayout) {
+	use image::GenericImageView;
+
+	let img = image::load_from_memory(bytes)
+		.unwrap();
+	let pixels = img.to_rgba8();
+
+	let dimensions = img.dimensions();
+
+	let size = Extent3d {
+		width: dimensions.0,
+		height: dimensions.1,
+		depth_or_array_layers: 1
+	};
+
+	let texture = device.create_texture(&TextureDescriptor {
+		label: Some("Atlas Texture"),
+		size: size,
+		// no mipmaps
+		mip_level_count: 1,
+		// no MSAA
+		sample_count: 1,
+		dimension: TextureDimension::D2,
+		format: TextureFormat::Rgba8UnormSrgb,
+		// use this texture in shaders, copy to it
+		usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST
+	});
+
+	// copy texture from host to device memory
+	queue.write_texture(
+		ImageCopyTexture {
+			texture: &texture,
+			mip_level: 0,
+			origin: Origin3d::ZERO,
+			aspect: TextureAspect::All
+		},
+		&pixels,
+		ImageDataLayout {
+			offset: 0,
+			// 4 BPP
+			bytes_per_row: NonZeroU32::new(4 * dimensions.0),
+			rows_per_image: NonZeroU32::new(dimensions.1)
+		},
+		size
+	);
+
+	let view = texture.create_view(&Default::default());
+	let sampler = device.create_sampler(&SamplerDescriptor {
+		address_mode_u: AddressMode::ClampToEdge,
+		address_mode_v: AddressMode::ClampToEdge,
+		address_mode_w: AddressMode::ClampToEdge,
+		mag_filter: FilterMode::Linear,
+		min_filter: FilterMode::Nearest,
+		mipmap_filter: FilterMode::Nearest,
+		..Default::default()
+	});
+
+	let layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
+		label: Some("Atlas Bind Group Layout"),
+		entries: &[
+			BindGroupLayoutEntry {
+				binding: 0,
+				// texture is only sampled in frag shader
+				visibility: ShaderStages::FRAGMENT,
+				ty: BindingType::Texture {
+					multisampled: false,
+					view_dimension: TextureViewDimension::D2,
+					sample_type: TextureSampleType::Float {
+						filterable: true
+					}
+				},
+				count: None
+			},
+			BindGroupLayoutEntry {
+				binding: 1,
+				visibility: ShaderStages::FRAGMENT,
+				ty: BindingType::Sampler(SamplerBindingType::Filtering),
+				count: None
+			}
+		]
+	});
+
+	let group = device.create_bind_group(&BindGroupDescriptor {
+		label: Some("Atlas Bind Group"),
+		layout: &layout,
+		entries: &[
+			BindGroupEntry {
+				binding: 0,
+				resource: BindingResource::TextureView(&view)
+			},
+			BindGroupEntry {
+				binding: 1,
+				resource: BindingResource::Sampler(&sampler)
+			}
+		]
+	});
+
+	(group, layout)
+}

+ 47 - 0
examples/viewer/src/render/camera.rs

@@ -0,0 +1,47 @@
+use cgmath::*;
+
+pub struct Camera {
+	eye: Point3<f32>,
+	target: Point3<f32>,
+	aspect_ratio: f32,
+	fov: Deg<f32>,
+	// near and far planes
+	near: f32,
+	far: f32
+}
+
+impl Camera {
+	/// Create a new camera, fov is in degrees
+	pub fn new(size: (f32, f32)) -> Self {
+		// TODO: accessors for positions
+		Self {
+			eye: (0.0, 0.0, 4.0).into(),
+			target: (0.0, 0.0, 0.0).into(),
+			aspect_ratio: size.0 / size.1,
+			fov: Deg(45.0),
+			near: 0.1,
+			far: 100.0
+		}
+	}
+
+	/// Returns the View*Projection matrix
+	pub fn build_matrix(&self) -> [[f32; 4]; 4] {
+		let view = Matrix4::look_at_rh(self.eye, self.target, Vector3::unit_y());
+		let proj = perspective(self.fov, self.aspect_ratio, self.near, self.far);
+
+		let res = OPENGL_TO_WGPU_MATRIX * proj * view;
+		res.into()
+	}
+
+	pub fn set_eye(&mut self, x: f32, y: f32, z: f32) {
+		self.eye = (x, y, z).into();
+	}
+}
+
+// fix cgmath's stuff
+const OPENGL_TO_WGPU_MATRIX: Matrix4<f32> = Matrix4::new(
+	1.0, 0.0, 0.0, 0.0,
+	0.0, 1.0, 0.0, 0.0,
+	0.0, 0.0, 0.5, 0.0,
+	0.0, 0.0, 0.5, 1.0,
+);

+ 47 - 0
examples/viewer/src/render/depth.rs

@@ -0,0 +1,47 @@
+use wgpu::*;
+
+pub struct DepthBuffer {
+	pub view: TextureView
+}
+
+impl DepthBuffer {
+	pub fn new(device: &Device, config: &SurfaceConfiguration) -> Self {
+		let size = Extent3d {
+			width: config.width,
+			height: config.height,
+			depth_or_array_layers: 1
+		};
+
+		let texture = device.create_texture(&TextureDescriptor {
+			label: Some("Depth buffer"),
+			size,
+			mip_level_count: 1,
+			sample_count: 1,
+			dimension: TextureDimension::D2,
+			format: Self::FORMAT,
+			usage: TextureUsages::RENDER_ATTACHMENT
+				| TextureUsages::TEXTURE_BINDING
+		});
+
+		let view = texture.create_view(&Default::default());
+		/*let sampler = device.create_sampler(&SamplerDescriptor {
+			address_mode_u: AddressMode::ClampToEdge,
+			address_mode_v: AddressMode::ClampToEdge,
+			address_mode_w: AddressMode::ClampToEdge,
+			mag_filter: FilterMode::Linear,
+			min_filter: FilterMode::Linear,
+			mipmap_filter: FilterMode::Nearest,
+			// the actual depth testing magic
+			compare: Some(CompareFunction::LessEqual),
+			lod_min_clamp: -100.0,
+			lod_max_clamp: 100.0,
+			..Default::default()
+		});*/
+
+		Self {
+			view
+		}
+	}
+
+	pub const FORMAT: TextureFormat = TextureFormat::Depth32Float;
+}

+ 49 - 0
examples/viewer/src/render/object.rs

@@ -0,0 +1,49 @@
+use std::mem::size_of;
+
+use bytemuck::{Pod, Zeroable};
+use cgmath::*;
+use wgpu::*;
+
+pub struct Object {
+	pub pos: Vector3<f32>,
+	pub scale: f32,
+	pub col: [f32; 4]
+}
+
+impl Object {
+	pub fn build(&self) -> ObjectData {
+		let pos = Matrix4::from_translation(self.pos);
+		let scale = Matrix4::from_scale(self.scale);
+		let model = pos * scale;
+
+		ObjectData {
+			model: model.into(),
+			col: self.col.clone()
+		}
+	}
+}
+
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+#[repr(C)]
+pub struct ObjectData {
+	model: [[f32; 4]; 4],
+	col: [f32; 4]
+}
+
+impl ObjectData {
+	pub fn layout<'a>() -> VertexBufferLayout<'a> {
+		VertexBufferLayout {
+			array_stride: size_of::<ObjectData>() as BufferAddress,
+			step_mode: VertexStepMode::Instance,
+			attributes: &Self::ATTRIBS
+		}
+	}
+
+	const ATTRIBS: [VertexAttribute; 5] = vertex_attr_array![
+		2 => Float32x4,
+		3 => Float32x4,
+		4 => Float32x4,
+		5 => Float32x4,
+		6 => Float32x4,
+	];
+}

+ 63 - 0
examples/viewer/src/render/pipeline.rs

@@ -0,0 +1,63 @@
+use crate::render::{
+	depth::*,
+	object::*,
+	vertex::*
+};
+
+use chair::Vertex;
+use wgpu::*;
+
+pub fn mesh(device: &Device, config: &SurfaceConfiguration, bind_layouts: &[&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: &[]
+	});
+
+	device.create_render_pipeline(&RenderPipelineDescriptor {
+		label: Some("Mesh Pipeline"),
+		layout: Some(&layout),
+		vertex: VertexState {
+			module: &module,
+			entry_point: "vs_main",
+			buffers: &[
+				TexturedVertex::layout(),
+				ObjectData::layout()
+			]
+		},
+		fragment: Some(FragmentState {
+			module: &module,
+			entry_point: "fs_main",
+			targets: &[Some(ColorTargetState {
+				format: config.format,
+				blend: Some(BlendState::REPLACE),
+				write_mask: ColorWrites::ALL
+			})]
+		}),
+		primitive: PrimitiveState {
+			topology: PrimitiveTopology::TriangleList,
+			strip_index_format: None,
+			front_face: FrontFace::Ccw,
+			cull_mode: None, //Some(Face::Back),
+			polygon_mode: PolygonMode::Fill,
+			unclipped_depth: false,
+			conservative: false
+		},
+		depth_stencil: Some(DepthStencilState {
+			format: DepthBuffer::FORMAT,
+			depth_write_enabled: true,
+			// this does the actual depth testing
+			depth_compare: CompareFunction::Less,
+			stencil: Default::default(),
+			bias: Default::default()
+		}),
+		multisample: MultisampleState {
+			count: 1,
+			mask: !0,
+			alpha_to_coverage_enabled: false
+		},
+		multiview: None
+	})
+}

+ 296 - 0
examples/viewer/src/render/renderer.rs

@@ -0,0 +1,296 @@
+use crate::render::{
+	atlas::*,
+	camera::*,
+	depth::*,
+	object::*,
+	pipeline,
+	vertex::*
+};
+
+use std::{
+	fs,
+	iter
+};
+
+use bytemuck::cast_slice;
+use chair::{Mesh, MeshReader};
+use wgpu::{
+	util::{BufferInitDescriptor, DeviceExt},
+	*
+};
+use winit::{
+	dpi::*,
+	window::{CursorGrabMode, Window}
+};
+
+pub type WindowSize = PhysicalSize<u32>;
+pub type MousePos = PhysicalPosition<f64>;
+
+pub struct Renderer {
+	surface: Surface,
+	device: Device,
+	queue: Queue,
+	config: SurfaceConfiguration,
+	size: WindowSize,
+
+	camera_bind_group: BindGroup,
+	mesh_pipeline: RenderPipeline,
+
+	// resources
+	texture_bind_group: BindGroup,
+	mesh: Mesh,
+
+	// frame state
+	depth: DepthBuffer,
+	camera: Camera,
+	uniforms: Buffer,
+	objects: Vec<Object>,
+	mesh_instances: Buffer
+}
+
+impl Renderer {
+	pub async fn new(window: &Window, path: &str) -> Self {
+		let size = window.inner_size();
+
+		let instance = Instance::new(Backends::all());
+		let surface = unsafe { instance.create_surface(window) };
+		let adapter = instance.request_adapter(
+			// want to find the fastest gpu first, must support rendering to our surface
+			&RequestAdapterOptions {
+				power_preference: PowerPreference::default(),
+				compatible_surface: Some(&surface),
+				// no software rendering please
+				force_fallback_adapter: false,
+			}
+		).await.expect("Failed to find a suitable gpu");
+
+		let (device, queue) = adapter.request_device(
+			// don't care about what the gpu supports
+			&DeviceDescriptor {
+				features: Features::empty(),
+				limits: get_device_limits(),
+				label: None
+			},
+			None // Trace path
+		).await.expect("Failed to find a suitable physical device");
+
+		let config = SurfaceConfiguration {
+			// using the surface to write to the window
+			usage: TextureUsages::RENDER_ATTACHMENT,
+			format: *surface.get_supported_formats(&adapter)
+				.first()
+				.expect("Surface has no preferred format"),
+			width: size.width,
+			height: size.height,
+			present_mode: PresentMode::AutoVsync,
+			alpha_mode: CompositeAlphaMode::Auto
+		};
+		surface.configure(&device, &config);
+
+		let depth = DepthBuffer::new(&device, &config);
+
+		// load mesh
+		let atlas = WholeAtlas;
+		let mesh_data = fs::read(path)
+			.expect("Failed to read mesh");
+		let mesh = MeshReader::new::<TexturedVertex>(&atlas, Some(""))
+			.create::<TexturedVertex>(&device, &mesh_data)
+			.expect("Failed to load mesh");
+
+		let mut objects = Vec::with_capacity(100);
+		for i in 0..100 {
+			let x = i % 10 - 5;
+			let y = i / 10 - 5;
+			let fade = (i as f32) / 100.0;
+
+			objects.push(Object {
+				pos: (x as f32, 0.0, y as f32).into(),
+				scale: fade,
+				col: [fade; 4]
+			});
+		}
+		let instance_data = objects.iter()
+			.map(Object::build)
+			.collect::<Vec<_>>();
+
+		// create buffers
+		let camera = Camera::new((config.width as f32, config.height as f32));
+		let uniforms = device.create_buffer_init(&BufferInitDescriptor {
+			label: Some("Uniform Buffer"),
+			contents: cast_slice(&camera.build_matrix()),
+			// need to modify it at every frame
+			usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST
+		});
+		let mesh_instances = device.create_buffer_init(&BufferInitDescriptor {
+			label: Some("Instance Buffer"),
+			contents: cast_slice(&instance_data),
+			usage: BufferUsages::VERTEX
+		});
+
+		// set up bind groups
+		let (texture_bind_group, texture_layout) = load_texture(&device, &queue, include_bytes!("../../texture.png"));
+		let (camera_bind_group, camera_layout) = bind_camera(&device, &uniforms);
+
+		// create mesh pipeline
+		let mesh_pipeline = pipeline::mesh(&device, &config, &[
+			&texture_layout,
+			&camera_layout
+		]);
+
+		// TODO: move elsewhere
+		window.set_cursor_grab(CursorGrabMode::Confined)
+			.expect("Failed to grab cursor");
+//		window.set_cursor_visible(false);
+
+		Self {
+			surface,
+			device,
+			queue,
+			config,
+			size,
+
+			camera_bind_group,
+			mesh_pipeline,
+
+			texture_bind_group,
+			mesh,
+
+			depth,
+			camera,
+			uniforms,
+			objects,
+			mesh_instances
+		}
+	}
+
+	pub fn resize(&mut self, size: WindowSize) {
+		self.size = size;
+		self.config.width = size.width;
+		self.config.height = size.height;
+		self.surface.configure(&self.device, &self.config);
+
+		// recreate anything that depends on surface configuration
+		self.depth = DepthBuffer::new(&self.device, &self.config);
+	}
+
+	pub fn recreate(&mut self) {
+		self.resize(self.size)
+	}
+
+	pub fn cursor_moved(&mut self, x: f64, y: f64) {
+		let center = self.center();
+		// map cursor from 0, size to -1.0, 1.0
+		let dx = (x - center.x) / (self.size.width as f64) * 6.28;
+		let dy = (y - center.y) / (self.size.height as f64) * 3.14;
+		let r = 4.0;
+		// TODO: correct x, z
+		self.camera.set_eye(r * dx.sin() as f32, r * dy.sin() as f32, r * dx.cos() as f32);
+
+		// update camera in uniforms
+		let matrix = self.camera.build_matrix();
+		let bytes = cast_slice(&matrix);
+		self.queue.write_buffer(&self.uniforms, 0, bytes);
+	}
+
+	pub fn render(&mut self) -> Result<(), SurfaceError> {
+		let output = self.surface.get_current_texture()?;
+		let view = output.texture.create_view(&TextureViewDescriptor::default());
+		let mut encoder = self.device.create_command_encoder(&CommandEncoderDescriptor {
+			label: Some("Render Encoder")
+		});
+
+		self.create_render_pass(&mut encoder, &view);
+
+		// submit commands for rendering
+		self.queue.submit(iter::once(encoder.finish()));
+		output.present();
+
+		Ok(())
+	}
+
+	pub fn center(&self) -> MousePos {
+		MousePos::new(self.size.width as f64 / 2.0, self.size.height as f64 / 2.0)
+	}
+
+	fn create_render_pass(&self, encoder: &mut CommandEncoder, view: &TextureView) {
+		let mut pass = encoder.begin_render_pass(&RenderPassDescriptor {
+			label: Some("Render Pass"),
+			color_attachments: &[Some(RenderPassColorAttachment {
+				view: &view,
+				// no multisampling
+				resolve_target: None,
+				ops: Operations {
+					// clear with this colour
+					load: LoadOp::Clear(Color {
+							r: 0.1,
+						g: 0.2,
+						b: 0.3,
+						a: 1.0
+					}),
+					// keep what is rendered
+					store: true
+				}
+			})],
+			// boy thats a mouthful
+			depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
+				view: &self.depth.view,
+				depth_ops: Some(Operations {
+					load: wgpu::LoadOp::Clear(1.0),
+					store: true
+				}),
+				stencil_ops: None
+			})
+		});
+
+		pass.set_pipeline(&self.mesh_pipeline);
+		pass.set_bind_group(0, &self.texture_bind_group, &[]);
+		pass.set_bind_group(1, &self.camera_bind_group, &[]);
+
+		let instances = self.objects.len() as u32;
+		pass.set_vertex_buffer(1, self.mesh_instances.slice(..));
+		self.mesh.draw_instanced(&mut pass, 0..instances);
+	}
+}
+
+fn get_device_limits() -> Limits {
+	let mut limits = Limits::default();
+	// compute isn't needed
+	limits.max_compute_workgroup_storage_size = 0;
+	limits.max_compute_invocations_per_workgroup = 0;
+	limits.max_compute_workgroup_size_x = 0;
+	limits.max_compute_workgroup_size_y = 0;
+	limits.max_compute_workgroup_size_z = 0;
+	limits.max_compute_workgroups_per_dimension = 0;
+	limits
+}
+
+fn bind_camera(device: &Device, buffer: &Buffer) -> (BindGroup, BindGroupLayout) {
+	let layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
+		label: Some("Camera bind group layout"),
+		entries: &[
+			BindGroupLayoutEntry {
+				binding: 0,
+				visibility: ShaderStages::VERTEX,
+				ty: BindingType::Buffer {
+					ty: BufferBindingType::Uniform,
+					// single camera, no need to resize it
+					has_dynamic_offset: false,
+					min_binding_size: None
+				},
+				count: None
+			}
+		]
+	});
+	let bind_group = device.create_bind_group(&BindGroupDescriptor {
+		label: Some("Camera bind group"),
+		layout: &layout,
+		entries: &[
+			BindGroupEntry {
+				binding: 0,
+				resource: buffer.as_entire_binding()
+			}
+		]
+	});
+
+	(bind_group, layout)
+}

+ 31 - 0
examples/viewer/src/render/vertex.rs

@@ -0,0 +1,31 @@
+use chair::*;
+use wgpu::*;
+
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+#[repr(C)]
+pub struct TexturedVertex {
+	pub pos: [f32; 3],
+	pub uvs: [f32; 2]
+}
+
+const ATTRIBS: &[VertexAttribute] = &vertex_attr_array![
+	0 => Float32x3,
+	1 => Float32x2
+];
+
+impl Vertex for TexturedVertex {
+	fn new(pos: [f32; 3], _: [f32; 4], _: [f32; 3], uvs: [f32; 2]) -> Self {
+		Self {
+			pos,
+			uvs
+		}
+	}
+
+	fn features() -> MeshFeatures {
+		features!(Textured)
+	}
+
+	fn attribs() -> &'static [VertexAttribute] {
+		ATTRIBS
+	}
+}

BIN
examples/viewer/texture.png


+ 5 - 4
src/io.rs

@@ -97,7 +97,8 @@ impl<'a, A: Atlas> MeshReader<'a, A> {
 
 	/// Extract vertices and indices from file contents
 	/// If using wgpu you can use `create` to also upload it to the gpu
-	pub fn read<V: Vertex>(&self, bytes: &[u8]) -> Result<(Vec<V>, Vec<Index>)> {
+	// TODO: remove debug
+	pub fn read<V: Vertex + std::fmt::Debug>(&self, bytes: &[u8]) -> Result<(Vec<V>, Vec<Index>)> {
 		let mut bytes = Cursor::new(bytes);
 		let bytes = &mut bytes;
 		let mut header = [0; 5];
@@ -313,7 +314,7 @@ impl<'a, A: Atlas> MeshReader<'a, A> {
 	}
 
 	/// Read and create a mesh on the GPU
-	pub fn create<V: Vertex>(&self, device: &Device, bytes: &[u8]) -> Result<Mesh> {
+	pub fn create<V: Vertex + std::fmt::Debug>(&self, device: &Device, bytes: &[u8]) -> Result<Mesh> {
 		let (vertices, indices) = self.read::<V>(bytes)?;
 		Ok(Mesh::new(device, &vertices, &indices))
 	}
@@ -345,8 +346,8 @@ fn read_f32(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
 }
 
 fn read_uv_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
-	// 64 instead of 127 to be able to evenly divide
-	Ok(bytes.read_i8()? as f32 / 64.0)
+	// 128 instead of 255 to be able to evenly divide
+	Ok(bytes.read_u8()? as f32 / 128.0)
 }
 
 fn read_index_u32(bytes: &mut Cursor<&[u8]>) -> Result<Index> {

+ 1 - 1
src/lib.rs

@@ -25,7 +25,7 @@ pub use crate::{
 	io::*
 };
 #[cfg(feature = "mesh")]
-pub use crate::mesh::{Index, Mesh};
+pub use crate::mesh::*;
 pub use crate::{
 	features::*,
 	vertex::*

+ 11 - 1
src/mesh.rs

@@ -2,6 +2,8 @@
 
 use crate::vertex::*;
 
+use std::ops::Range;
+
 use bytemuck::cast_slice;
 use wgpu::{
 	util::{BufferInitDescriptor, DeviceExt},
@@ -42,11 +44,19 @@ impl Mesh {
 		}
 	}
 
-	/// Draw a single instance of this mesh
+	/// Draw a single instance of this mesh.
 	/// Drawing indexed or indirectly is prefered.
 	pub fn draw<'a>(&'a self, pass: &mut RenderPass<'a>) {
 		pass.set_vertex_buffer(0, self.vertices.slice(..));
 		pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT);
 		pass.draw_indexed(0..self.index_count, 0, 0..1);
 	}
+
+	/// Draw multiple instances of this mesh, the instance buffer must be bound already.
+	/// Drawing indirectly is prefered.
+	pub fn draw_instanced<'a>(&'a self, pass: &mut RenderPass<'a>, instances: Range<u32>) {
+		pass.set_vertex_buffer(0, self.vertices.slice(..));
+		pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT);
+		pass.draw_indexed(0..self.index_count, 0, instances);
+	}
 }

+ 10 - 8
src/vertex.rs

@@ -9,8 +9,9 @@ pub use impls::*;
 
 use crate::features::*;
 
-use bytemuck::{Pod, Zeroable};
-#[cfg(feature = "wgpu")]
+// exported for easy implementing
+pub use bytemuck::{Pod, Zeroable};
+#[cfg(feature = "mesh")]
 use wgpu::*;
 
 /// The vertex trait implemented by vertex types
@@ -25,6 +26,10 @@ use wgpu::*;
 /// 	pub pos: [f32; 3]
 /// }
 ///
+/// const ATTRIBS: &[VertexAttribute] = &vertex_attr_array![
+/// 	0 => Float32x3
+/// ]
+///
 /// impl Vertex for BasicVertex {
 /// 	fn new(pos: [f32; 3], _: [f32; 4], _: [f32; 3], _: [f32; 2]) -> Self {
 /// 		Self {
@@ -36,11 +41,8 @@ use wgpu::*;
 ///			features!()
 ///		}
 ///
-/// 	#[cfg(feature = "wgpu")]
 /// 	fn attribs() -> &'static [VertexAttribute] {
-/// 		&vertex_attr_array![
-/// 			0 => Float32x3
-/// 		]
+/// 		ATTRIBS
 /// 	}
 /// }
 /// ```
@@ -53,11 +55,11 @@ pub trait Vertex: Pod + Zeroable {
 	fn features() -> MeshFeatures;
 
 	/// Return the attributes for each field in this vertex format
-	#[cfg(feature = "wgpu")]
+	#[cfg(feature = "mesh")]
 	fn attribs() -> &'static [VertexAttribute];
 
 	/// Return the vertex buffer layout for this vertex format
-	#[cfg(feature = "wgpu")]
+	#[cfg(feature = "mesh")]
 	fn layout() -> VertexBufferLayout<'static> {
 		VertexBufferLayout {
 			array_stride: std::mem::size_of::<Self>() as BufferAddress,

+ 11 - 8
src/vertex/impls.rs

@@ -6,7 +6,7 @@ use crate::{
 };
 
 use bytemuck::{Pod, Zeroable};
-#[cfg(feature = "wgpu")]
+#[cfg(feature = "mesh")]
 use wgpu::*;
 
 /// A vertex that just has position
@@ -28,9 +28,9 @@ impl Vertex for BasicVertex {
 		features!()
 	}
 
-	#[cfg(feature = "wgpu")]
+	#[cfg(feature = "mesh")]
 	fn attribs() -> &'static [VertexAttribute] {
-		&vertex_attrib_array![
+		&vertex_attr_array![
 			0 => Float32x3
 		]
 	}
@@ -56,11 +56,14 @@ impl Vertex for ColouredVertex {
 		features!(Coloured)
 	}
 
-	#[cfg(feature = "wgpu")]
+	#[cfg(feature = "mesh")]
 	fn attribs() -> &'static [VertexAttribute] {
-		&vertex_attrib_array![
-			0 => Float32x3,
-			1 => Float32x4
-		]
+		ATTRIBS
 	}
 }
+
+#[cfg(feature = "mesh")]
+const ATTRIBS: &[VertexAttribute] = &vertex_attr_array![
+	0 => Float32x3,
+	1 => Float32x4
+];