use std::collections::{HashSet,HashMap};
use strafesnet_common::integer::fixed_types::{F128_64,F192_96,F256_128};
use strafesnet_common::integer::vec3::Vector3;
use strafesnet_common::model::{self,MeshId,PolygonIter};
use strafesnet_common::integer::{self,vec3,Fixed,Planar64,Planar64Vec3,Ratio};
use strafesnet_common::physics::Time;
use crate::mesh_query::{MeshQuery,MeshTopology,DirectedEdge,UndirectedEdge};

struct AsRefHelper<T>(T);
impl<T> AsRef<T> for AsRefHelper<T>{
	fn as_ref(&self)->&T{
		&self.0
	}
}

#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct MeshVertId(u32);
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct MeshFaceId(u32);

#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct SubmeshVertId(u32);
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct SubmeshEdgeId(u32);
/// DirectedEdgeId refers to an EdgeId when undirected.
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct SubmeshDirectedEdgeId(u32);
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct SubmeshFaceId(u32);

impl UndirectedEdge for SubmeshEdgeId{
	type DirectedEdge=SubmeshDirectedEdgeId;
	fn as_directed(self,parity:bool)->SubmeshDirectedEdgeId{
		SubmeshDirectedEdgeId(self.0|((parity as u32)<<(u32::BITS-1)))
	}
}
impl DirectedEdge for SubmeshDirectedEdgeId{
	type UndirectedEdge=SubmeshEdgeId;
	fn as_undirected(self)->SubmeshEdgeId{
		SubmeshEdgeId(self.0&!(1<<(u32::BITS-1)))
	}
	fn parity(&self)->bool{
		self.0&(1<<(u32::BITS-1))!=0
	}
}

//use Unit32 #[repr(C)] for map files
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
struct Face{
	normal:Planar64Vec3,
	dot:Planar64,
}
#[derive(Debug)]
struct Vert(Planar64Vec3);
#[derive(Debug)]
struct FaceRefs{
	// I didn't write it down, but I assume the edges are directed
	// clockwise when looking towards the face normal, i.e. right hand rule.
	edges:Vec<SubmeshDirectedEdgeId>,
	//verts are redundant, use edge[i].verts[0]
	//verts:Vec<VertId>,
}
#[derive(Debug)]
struct EdgeRefs{
	faces:[SubmeshFaceId;2],//left, right
	verts:[SubmeshVertId;2],//start, end
}
#[derive(Debug)]
struct VertRefs{
	faces:Vec<SubmeshFaceId>,
	// edges are always directed away from the vert
	edges:Vec<SubmeshDirectedEdgeId>,
}
#[derive(Debug)]
pub struct PhysicsMeshData{
	//this contains all real and virtual faces used in both the complete mesh and convex submeshes
	//faces are sorted such that all faces that belong to the complete mesh appear first, and then
	//all remaining faces are virtual to operate internal logic of the face crawler
	//and cannot be part of a physics collision
	//virtual faces are only used in convex submeshes.
	faces:Vec<Face>,//MeshFaceId indexes this list
	verts:Vec<Vert>,//MeshVertId indexes this list
}
#[derive(Debug)]
pub struct PhysicsMeshTopology{
	//mapping of local ids to PhysicsMeshData ids
	faces:Vec<MeshFaceId>,//SubmeshFaceId indexes this list
	verts:Vec<MeshVertId>,//SubmeshVertId indexes this list
	//all ids here are local to this object
	face_topology:Vec<FaceRefs>,
	edge_topology:Vec<EdgeRefs>,
	vert_topology:Vec<VertRefs>,
}
#[derive(Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct PhysicsMeshId(u32);
impl Into<MeshId> for PhysicsMeshId{
	fn into(self)->MeshId{
		MeshId::new(self.0)
	}
}
impl From<MeshId> for PhysicsMeshId{
	fn from(value:MeshId)->Self{
		Self::new(value.get())
	}
}
#[derive(Debug,Default,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct PhysicsSubmeshId(u32);
pub struct PhysicsMesh{
	data:PhysicsMeshData,
	// The complete mesh is unused at this time.
	// complete_mesh:PhysicsMeshTopology,
	// Submeshes are guaranteed to be convex and may contain
	// "virtual" faces which are not part of the complete mesh.
	// Physics calculations should never resolve to hitting
	// a virtual face.
	submeshes:Vec<PhysicsMeshTopology>,
}
impl PhysicsMesh{
	pub fn unit_cube()->Self{
		//go go gadget debug print mesh
		let data=PhysicsMeshData{
			faces:vec![
				Face{normal:vec3::raw_xyz( 4294967296, 0, 0),dot:Planar64::raw(4294967296)},
				Face{normal:vec3::raw_xyz( 0, 4294967296, 0),dot:Planar64::raw(4294967296)},
				Face{normal:vec3::raw_xyz( 0, 0, 4294967296),dot:Planar64::raw(4294967296)},
				Face{normal:vec3::raw_xyz(-4294967296, 0, 0),dot:Planar64::raw(4294967296)},
				Face{normal:vec3::raw_xyz( 0,-4294967296, 0),dot:Planar64::raw(4294967296)},
				Face{normal:vec3::raw_xyz( 0, 0,-4294967296),dot:Planar64::raw(4294967296)}
			],
			verts:vec![
				Vert(vec3::raw_xyz( 4294967296,-4294967296,-4294967296)),
				Vert(vec3::raw_xyz( 4294967296, 4294967296,-4294967296)),
				Vert(vec3::raw_xyz( 4294967296, 4294967296, 4294967296)),
				Vert(vec3::raw_xyz( 4294967296,-4294967296, 4294967296)),
				Vert(vec3::raw_xyz(-4294967296, 4294967296,-4294967296)),
				Vert(vec3::raw_xyz(-4294967296, 4294967296, 4294967296)),
				Vert(vec3::raw_xyz(-4294967296,-4294967296, 4294967296)),
				Vert(vec3::raw_xyz(-4294967296,-4294967296,-4294967296))
			]
		};
		let mesh_topology=PhysicsMeshTopology{
			faces:(0..data.faces.len() as u32).map(MeshFaceId::new).collect(),
			verts:(0..data.verts.len() as u32).map(MeshVertId::new).collect(),
			face_topology:vec![
				FaceRefs{edges:vec![SubmeshDirectedEdgeId((9223372036854775808u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775809u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775810u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(3)]},
				FaceRefs{edges:vec![SubmeshDirectedEdgeId((9223372036854775812u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775813u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(6),SubmeshDirectedEdgeId(1)]},
				FaceRefs{edges:vec![SubmeshDirectedEdgeId(7),SubmeshDirectedEdgeId(2),SubmeshDirectedEdgeId((9223372036854775814u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775816u64-(1<<63)+(1<<31)) as u32)]},
				FaceRefs{edges:vec![SubmeshDirectedEdgeId(8),SubmeshDirectedEdgeId(5),SubmeshDirectedEdgeId((9223372036854775817u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(10)]},
				FaceRefs{edges:vec![SubmeshDirectedEdgeId((9223372036854775815u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775818u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(11),SubmeshDirectedEdgeId((9223372036854775811u64-(1<<63)+(1<<31)) as u32)]},
				FaceRefs{edges:vec![SubmeshDirectedEdgeId(4),SubmeshDirectedEdgeId(0),SubmeshDirectedEdgeId((9223372036854775819u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(9)]}
			],
			edge_topology:vec![
				EdgeRefs{faces:[SubmeshFaceId(0),SubmeshFaceId(5)],verts:[SubmeshVertId(0),SubmeshVertId(1)]},
				EdgeRefs{faces:[SubmeshFaceId(0),SubmeshFaceId(1)],verts:[SubmeshVertId(1),SubmeshVertId(2)]},
				EdgeRefs{faces:[SubmeshFaceId(0),SubmeshFaceId(2)],verts:[SubmeshVertId(2),SubmeshVertId(3)]},
				EdgeRefs{faces:[SubmeshFaceId(4),SubmeshFaceId(0)],verts:[SubmeshVertId(0),SubmeshVertId(3)]},
				EdgeRefs{faces:[SubmeshFaceId(1),SubmeshFaceId(5)],verts:[SubmeshVertId(1),SubmeshVertId(4)]},
				EdgeRefs{faces:[SubmeshFaceId(1),SubmeshFaceId(3)],verts:[SubmeshVertId(4),SubmeshVertId(5)]},
				EdgeRefs{faces:[SubmeshFaceId(2),SubmeshFaceId(1)],verts:[SubmeshVertId(2),SubmeshVertId(5)]},
				EdgeRefs{faces:[SubmeshFaceId(4),SubmeshFaceId(2)],verts:[SubmeshVertId(3),SubmeshVertId(6)]},
				EdgeRefs{faces:[SubmeshFaceId(2),SubmeshFaceId(3)],verts:[SubmeshVertId(5),SubmeshVertId(6)]},
				EdgeRefs{faces:[SubmeshFaceId(3),SubmeshFaceId(5)],verts:[SubmeshVertId(4),SubmeshVertId(7)]},
				EdgeRefs{faces:[SubmeshFaceId(4),SubmeshFaceId(3)],verts:[SubmeshVertId(6),SubmeshVertId(7)]},
				EdgeRefs{faces:[SubmeshFaceId(5),SubmeshFaceId(4)],verts:[SubmeshVertId(0),SubmeshVertId(7)]}
			],
			vert_topology:vec![
				VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(4),SubmeshFaceId(5)],edges:vec![SubmeshDirectedEdgeId((9223372036854775811u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775819u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775808u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(5),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId((9223372036854775812u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(0),SubmeshDirectedEdgeId((9223372036854775809u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(2),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId(1),SubmeshDirectedEdgeId((9223372036854775810u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775814u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(2),SubmeshFaceId(4)],edges:vec![SubmeshDirectedEdgeId(2),SubmeshDirectedEdgeId(3),SubmeshDirectedEdgeId((9223372036854775815u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(3),SubmeshFaceId(5),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId(4),SubmeshDirectedEdgeId((9223372036854775817u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775813u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(2),SubmeshFaceId(3),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId(5),SubmeshDirectedEdgeId(6),SubmeshDirectedEdgeId((9223372036854775816u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(2),SubmeshFaceId(3),SubmeshFaceId(4)],edges:vec![SubmeshDirectedEdgeId(7),SubmeshDirectedEdgeId(8),SubmeshDirectedEdgeId((9223372036854775818u64-(1<<63)+(1<<31)) as u32)]},
				VertRefs{faces:vec![SubmeshFaceId(4),SubmeshFaceId(3),SubmeshFaceId(5)],edges:vec![SubmeshDirectedEdgeId(10),SubmeshDirectedEdgeId(11),SubmeshDirectedEdgeId(9)]}
			]
		};
		Self{
			data,
			// complete_mesh:mesh_topology.clone(),
			submeshes:vec![mesh_topology],
		}
	}
	pub fn unit_cylinder()->Self{
		Self::unit_cube()
	}
	#[inline]
	pub fn complete_mesh(&self)->&PhysicsMeshTopology{
		// If there is exactly one submesh, then the complete mesh is identical to it.
		if self.submeshes.len()==1{
			self.submeshes.first().unwrap()
		}else{
			panic!("PhysicsMesh complete mesh is not known");
		}
	}
	#[inline]
	pub fn complete_mesh_view(&self)->PhysicsMeshView<'_>{
		PhysicsMeshView{
			data:&self.data,
			topology:self.complete_mesh(),
		}
	}
	#[inline]
	pub fn submeshes(&self)->&[PhysicsMeshTopology]{
		&self.submeshes
	}
	#[inline]
	pub fn submesh_view(&self,submesh_id:PhysicsSubmeshId)->PhysicsMeshView<'_>{
		PhysicsMeshView{
			data:&self.data,
			topology:&self.submeshes()[submesh_id.get() as usize],
		}
	}
	pub fn submesh_views(&self)->impl Iterator<Item=PhysicsMeshView<'_>>{
		self.submeshes().iter().map(|topology|PhysicsMeshView{
			data:&self.data,
			topology,
		})
	}
}

//mesh builder code
#[derive(Default,Clone)]
struct VertRefGuy{
	edges:HashSet<SubmeshDirectedEdgeId>,
	faces:HashSet<SubmeshFaceId>,
}
#[derive(Clone,Hash,Eq,PartialEq)]
struct EdgeRefVerts([SubmeshVertId;2]);
impl EdgeRefVerts{
	const fn new(v0:SubmeshVertId,v1:SubmeshVertId)->(Self,bool){
		(if v0.0<v1.0{
			Self([v0,v1])
		}else{
			Self([v1,v0])
		},v0.0<v1.0)
	}
}
struct EdgeRefFaces([SubmeshFaceId;2]);
impl EdgeRefFaces{
	const fn new()->Self{
		Self([SubmeshFaceId(0);2])
	}
	fn push(&mut self,i:usize,face_id:SubmeshFaceId){
		self.0[i]=face_id;
	}
}
struct FaceRefEdges(Vec<SubmeshDirectedEdgeId>);
#[derive(Default)]
struct EdgePool{
	edge_guys:Vec<(EdgeRefVerts,EdgeRefFaces)>,
	edge_id_from_guy:HashMap<EdgeRefVerts,SubmeshEdgeId>,
}
impl EdgePool{
	fn push(&mut self,edge_ref_verts:EdgeRefVerts)->(&mut EdgeRefFaces,SubmeshEdgeId){
		let edge_id=*self.edge_id_from_guy.entry(edge_ref_verts.clone()).or_insert_with(||{
			let edge_id=SubmeshEdgeId::new(self.edge_guys.len() as u32);
			self.edge_guys.push((edge_ref_verts,EdgeRefFaces::new()));
			edge_id
		});
		(&mut self.edge_guys[edge_id.get() as usize].1,edge_id)
	}
}

#[derive(Debug)]
pub enum PhysicsMeshError{
	ZeroVertices,
	NoPhysicsGroups,
}
impl std::fmt::Display for PhysicsMeshError{
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f,"{self:?}")
	}
}
impl std::error::Error for PhysicsMeshError{}

impl TryFrom<&model::Mesh> for PhysicsMesh{
	type Error=PhysicsMeshError;
	fn try_from(mesh:&model::Mesh)->Result<Self,PhysicsMeshError>{
		if mesh.unique_pos.len()==0{
			return Err(PhysicsMeshError::ZeroVertices);
		}
		// An empty physics mesh is a waste of resources
		if mesh.physics_groups.len()==0{
			return Err(PhysicsMeshError::NoPhysicsGroups);
		}
		let verts=mesh.unique_pos.iter().copied().map(Vert).collect();
		//TODO: fix submeshes
		//flat map mesh.physics_groups[$1].groups.polys()[$2] as face_id
		//lower face_id points to upper face_id
		//the same face is not allowed to be in multiple polygon groups
		// because SubmeshFaceId -> CompleteMeshFaceId -> SubmeshFaceId is ambiguous
		// when multiple SubmeshFaceId point to one MeshFaceId
		let mut faces=Vec::new();
		let mut face_id_from_face=HashMap::new();
		let mesh_topologies:Vec<PhysicsMeshTopology>=mesh.physics_groups.iter().map(|physics_group|{
			//construct submesh
			let mut submesh_faces=Vec::new();//these contain a map from submeshId->meshId
			let mut submesh_verts=Vec::new();
			let mut submesh_vert_id_from_mesh_vert_id=HashMap::<MeshVertId,SubmeshVertId>::new();
			//lazy closure
			let mut get_submesh_vert_id=|vert_id:MeshVertId|*submesh_vert_id_from_mesh_vert_id.entry(vert_id).or_insert_with(||{
				let submesh_vert_id=SubmeshVertId::new(submesh_verts.len() as u32);
				submesh_verts.push(vert_id);
				submesh_vert_id
			});
			let mut edge_pool=EdgePool::default();
			let mut vert_ref_guys=vec![VertRefGuy::default();mesh.unique_pos.len()];
			let mut face_ref_guys=Vec::new();
			for polygon_group_id in &physics_group.groups{
				let polygon_group=&mesh.polygon_groups[polygon_group_id.get() as usize];
				for poly_vertices in polygon_group.polys(){
					let submesh_face_id=SubmeshFaceId::new(submesh_faces.len() as u32);
					//one face per poly
					let mut normal=Vector3::new([Fixed::ZERO,Fixed::ZERO,Fixed::ZERO]);
					let len=poly_vertices.len();
					let face_edges=poly_vertices.into_iter().enumerate().map(|(i,vert_id)|{
						let vert0_id=MeshVertId::new(mesh.unique_vertices[vert_id.get() as usize].pos.get() as u32);
						let vert1_id=MeshVertId::new(mesh.unique_vertices[poly_vertices[(i+1)%len].get() as usize].pos.get() as u32);
						//index submesh verts
						let submesh_vert0_id=get_submesh_vert_id(vert0_id);
						let submesh_vert1_id=get_submesh_vert_id(vert1_id);
						//https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal (Newell's Method)
						let v0=mesh.unique_pos[vert0_id.get() as usize];
						let v1=mesh.unique_pos[vert1_id.get() as usize];
						normal+=Vector3::new([
							(v0.y-v1.y)*(v0.z+v1.z),
							(v0.z-v1.z)*(v0.x+v1.x),
							(v0.x-v1.x)*(v0.y+v1.y),
						]);
						//get/create edge and push face into it
						let (edge_ref_verts,is_sorted)=EdgeRefVerts::new(submesh_vert0_id,submesh_vert1_id);
						let (edge_ref_faces,edge_id)=edge_pool.push(edge_ref_verts);
						//polygon vertices as assumed to be listed clockwise
						//populate the edge face on the left or right depending on how the edge vertices got sorted
						edge_ref_faces.push(!is_sorted as usize,submesh_face_id);
						//index edges & face into vertices
						{
							let vert_ref_guy=&mut vert_ref_guys[submesh_vert0_id.get() as usize];
							vert_ref_guy.edges.insert(edge_id.as_directed(is_sorted));
							vert_ref_guy.faces.insert(submesh_face_id);
							vert_ref_guys[submesh_vert1_id.get() as usize].edges.insert(edge_id.as_directed(!is_sorted));
						}
						//return directed_edge_id
						edge_id.as_directed(is_sorted)
					}).collect();
					let mut dot=Fixed::ZERO;
					// find the average dot
					for &v in poly_vertices{
						dot+=normal.dot(mesh.unique_pos[mesh.unique_vertices[v.get() as usize].pos.get() as usize]);
					}
					//assume face hash is stable, and there are no flush faces...
					let face=Face{
						normal:(normal/len as i64).divide().narrow_64().unwrap(),
						dot:(dot/(len*len) as i64).narrow_64().unwrap(),
					};
					let face_id=*face_id_from_face.entry(face).or_insert_with(||{
						let face_id=MeshFaceId::new(faces.len() as u32);
						faces.push(face);
						face_id
					});
					submesh_faces.push(face_id);
					face_ref_guys.push(FaceRefEdges(face_edges));
				}
			}
			PhysicsMeshTopology{
				faces:submesh_faces,
				verts:submesh_verts,
				face_topology:face_ref_guys.into_iter().map(|FaceRefEdges(edges)|{
					FaceRefs{edges}
				}).collect(),
				edge_topology:edge_pool.edge_guys.into_iter().map(|(EdgeRefVerts(verts),EdgeRefFaces(faces))|
					EdgeRefs{faces,verts}
				).collect(),
				vert_topology:vert_ref_guys.into_iter().map(|VertRefGuy{edges,faces}|
					VertRefs{
						edges:edges.into_iter().collect(),
						faces:faces.into_iter().collect(),
					}
				).collect(),
			}
		}).collect();
		Ok(Self{
			data:PhysicsMeshData{
				faces,
				verts,
			},
			// complete_mesh:None,
			submeshes:mesh_topologies,
		})
	}
}

#[derive(Debug,Clone,Copy)]
pub struct PhysicsMeshView<'a>{
	data:&'a PhysicsMeshData,
	topology:&'a PhysicsMeshTopology,
}
impl MeshQuery for PhysicsMeshView<'_>{
	type Position=Planar64Vec3;
	type Direction=Planar64Vec3;
	type Normal=Planar64Vec3;
	type Offset=Planar64;
	fn face_nd(&self,face_id:SubmeshFaceId)->(Planar64Vec3,Planar64){
		let face_idx=self.topology.faces[face_id.get() as usize].get() as usize;
		(self.data.faces[face_idx].normal,self.data.faces[face_idx].dot)
	}
	fn hint_point(&self)->Planar64Vec3{
		// invariant: meshes always encompass the origin
		vec3::zero()
	}
	fn farthest_vert(&self,dir:Planar64Vec3)->SubmeshVertId{
		//this happens to be well-defined.  there are no virtual virtices
		SubmeshVertId::new(
			self.topology.verts.iter()
			.enumerate()
			.max_by_key(|&(_,&vert_id)|
				dir.dot(self.data.verts[vert_id.get() as usize].0)
			)
			//assume there is more than zero vertices.
			.unwrap().0 as u32
		)
	}
	//ideally I never calculate the vertex position, but I have to for the graphical meshes...
	fn vert(&self,vert_id:SubmeshVertId)->Planar64Vec3{
		let vert_idx=self.topology.verts[vert_id.get() as usize].get() as usize;
		self.data.verts[vert_idx].0
	}
	fn edge_n(&self,edge_id:Self::Edge)->Self::Direction{
		let &[v0,v1]=self.edge_verts(edge_id).as_ref();
		self.vert(v1)-self.vert(v0)
	}
	fn directed_edge_n(&self,directed_edge_id:Self::DirectedEdge)->Self::Direction{
		let &[v0,v1]=self.edge_verts(directed_edge_id.as_undirected()).as_ref();
		(self.vert(v1)-self.vert(v0))*((directed_edge_id.parity() as i64)*2-1)
	}
}
impl MeshTopology for PhysicsMeshView<'_>{
	type Face=SubmeshFaceId;
	type Edge=SubmeshEdgeId;
	type DirectedEdge=SubmeshDirectedEdgeId;
	type Vert=SubmeshVertId;
	fn for_each_vert_edge(&self,vert_id:Self::Vert,f:impl FnMut(Self::DirectedEdge)){
		self.topology.vert_topology[vert_id.get() as usize].edges.iter().copied().for_each(f);
	}
	fn for_each_vert_face(&self,vert_id:Self::Vert,f:impl FnMut(Self::Face)){
		self.topology.vert_topology[vert_id.get() as usize].faces.iter().copied().for_each(f);
	}
	fn edge_faces(&self,edge_id:Self::Edge)->impl AsRef<[Self::Face;2]>{
		AsRefHelper(self.topology.edge_topology[edge_id.get() as usize].faces)
	}
	fn edge_verts(&self,edge_id:Self::Edge)->impl AsRef<[Self::Vert;2]>{
		AsRefHelper(self.topology.edge_topology[edge_id.get() as usize].verts)
	}
	fn for_each_face_vert(&self,_face_id:Self::Face,_f:impl FnMut(Self::Vert)){
		unimplemented!()
	}
	fn for_each_face_edge(&self,face_id:Self::Face,f:impl FnMut(Self::DirectedEdge)){
		self.topology.face_topology[face_id.get() as usize].edges.iter().copied().for_each(f);
	}
}

#[derive(Debug)]
pub struct PhysicsMeshTransform{
	pub vertex:integer::Planar64Affine3,
	pub normal:integer::mat3::Matrix3<F128_64>,
	pub det:F192_96,
}
impl PhysicsMeshTransform{
	pub fn new(transform:integer::Planar64Affine3)->Self{
		Self{
			normal:transform.matrix3.adjugate().transpose(),
			det:transform.matrix3.det(),
			vertex:transform,
		}
	}
}

#[derive(Debug,Clone,Copy)]
pub struct TransformedMesh<'a>{
	view:PhysicsMeshView<'a>,
	transform:&'a PhysicsMeshTransform,
}
impl TransformedMesh<'_>{
	pub const fn new<'a>(
		view:PhysicsMeshView<'a>,
		transform:&'a PhysicsMeshTransform,
	)->TransformedMesh<'a>{
		TransformedMesh{
			view,
			transform,
		}
	}
	pub fn verts<'a>(&'a self)->impl Iterator<Item=Vector3<F128_64>>+'a{
		self.view.data.verts.iter().map(|&Vert(pos)|self.transform.vertex.transform_point3(pos))
	}
}
impl MeshQuery for TransformedMesh<'_>{
	type Direction=Planar64Vec3;
	type Position=Planar64Vec3;
	type Normal=Vector3<F192_96>;
	type Offset=F256_128;
	fn face_nd(&self,face_id:SubmeshFaceId)->(Self::Normal,Self::Offset){
		let (n,d)=self.view.face_nd(face_id);
		let transformed_n=self.transform.normal*n;
		let transformed_d=d*self.transform.det+transformed_n.dot(self.transform.vertex.translation);
		(transformed_n,transformed_d)
	}
	fn vert(&self,vert_id:SubmeshVertId)->Planar64Vec3{
		// wrap for speed
		self.transform.vertex.transform_point3(self.view.vert(vert_id)).wrap_64()
	}
	fn hint_point(&self)->Planar64Vec3{
		self.transform.vertex.translation
	}
	fn farthest_vert(&self,dir:Planar64Vec3)->SubmeshVertId{
		//this happens to be well-defined.  there are no virtual virtices
		SubmeshVertId::new(
			self.view.topology.verts.iter()
			.enumerate()
			.max_by_key(|&(_,&vert_id)|
				dir.dot(self.transform.vertex.transform_point3(self.view.data.verts[vert_id.get() as usize].0))
			)
			//assume there is more than zero vertices.
			.unwrap().0 as u32
		)
	}
	fn edge_n(&self,edge_id:Self::Edge)->Self::Direction{
		let &[v0,v1]=self.edge_verts(edge_id).as_ref();
		self.vert(v1)-self.vert(v0)
	}
	fn directed_edge_n(&self,directed_edge_id:Self::DirectedEdge)->Self::Direction{
		let &[v0,v1]=self.edge_verts(directed_edge_id.as_undirected()).as_ref();
		(self.vert(v1)-self.vert(v0))*((directed_edge_id.parity() as i64)*2-1)
	}
}
impl MeshTopology for TransformedMesh<'_>{
	type Face=SubmeshFaceId;
	type Edge=SubmeshEdgeId;
	type DirectedEdge=SubmeshDirectedEdgeId;
	type Vert=SubmeshVertId;
	#[inline]
	fn for_each_vert_edge(&self,vert_id:Self::Vert,f:impl FnMut(Self::DirectedEdge)){
		self.view.for_each_vert_edge(vert_id,f)
	}
	#[inline]
	fn for_each_vert_face(&self,vert_id:Self::Vert,f:impl FnMut(Self::Face)){
		self.view.for_each_vert_face(vert_id,f)
	}
	#[inline]
	fn edge_faces(&self,edge_id:Self::Edge)->impl AsRef<[Self::Face;2]>{
		self.view.edge_faces(edge_id)
	}
	#[inline]
	fn edge_verts(&self,edge_id:Self::Edge)->impl AsRef<[Self::Vert;2]>{
		self.view.edge_verts(edge_id)
	}
	fn for_each_face_vert(&self,_face_id:Self::Face,_f:impl FnMut(Self::Vert)){
		unimplemented!()
	}
	#[inline]
	fn for_each_face_edge(&self,face_id:Self::Face,f:impl FnMut(Self::DirectedEdge)){
		self.view.for_each_face_edge(face_id,f)
	}
}

pub type GigaTime=Ratio<F256_128,F256_128>;
pub fn into_giga_time(time:Time,relative_to:Time)->GigaTime{
	let r=(time-relative_to).to_ratio();
	Ratio::new(r.num.widen_256(),r.den.widen_256())
}
