io.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. use crate::{
  2. atlas::*,
  3. features::*,
  4. mesh::*,
  5. vertex::*
  6. };
  7. use std::io::{Cursor, Read};
  8. use byteorder::*;
  9. use log::*;
  10. use thiserror::*;
  11. use wgpu::*;
  12. #[derive(Debug, Error)]
  13. pub enum Error {
  14. #[error("failed to read mesh")]
  15. Io(#[from] std::io::Error),
  16. #[error("wrong mesh header")]
  17. WrongHeader([u8; 5]),
  18. #[error("unknown mesh version {0}")]
  19. UnknownVersion(u8),
  20. #[error("mesh contains banned features: {0:?}")]
  21. BannedFeatures(MeshFeatures),
  22. #[error("mesh does not contain required features: {0:?}")]
  23. MissingFeatures(MeshFeatures),
  24. #[error("non-utf8 texture name #{0}")]
  25. InvalidTextureName(u8),
  26. #[error("atlas does not contain texture '{0}'")]
  27. MissingTexture(String),
  28. #[error("object {0} uses an unknown texture index")]
  29. UnknownTexture(u8),
  30. #[error("unknown colour index {0}")]
  31. UnknownColour(u16)
  32. }
  33. pub type Result<T> = std::result::Result<T, Error>;
  34. /// Configuration for reading meshes
  35. /// # Examples
  36. /// ```
  37. /// # use chair::*;
  38. /// # struct EmptyAtlas;
  39. /// # impl Atlas for EmptyAtlas { fn get(&self, name: &str) -> Option<&AtlasRegion> { None } }
  40. /// # let atlas = EmptyAtlas;
  41. /// let reader = MeshReader::new::<BasicVertex>(&atlas, None)
  42. /// // refuse to load any meshes that can be animated, even though the information would be discarded
  43. /// .ban_feature(MeshFeature::Rigged);
  44. /// // Minimal file with no vertices
  45. /// let bytes = b"CHAIR\x00\x00\x00\x00\x00\x00\x00";
  46. /// reader.read::<BasicVertex>(bytes).unwrap();
  47. /// ```
  48. ///
  49. pub struct MeshReader<'a, A: Atlas> {
  50. atlas: &'a A,
  51. fallback: Option<&'a AtlasRegion>,
  52. banned: MeshFeatures,
  53. required: MeshFeatures
  54. }
  55. impl<'a, A: Atlas> MeshReader<'a, A> {
  56. pub fn new<V: Vertex>(atlas: &'a A, fallback: Option<&str>) -> Self {
  57. Self {
  58. atlas,
  59. fallback: match fallback.map(|name| atlas.get(name)) {
  60. Some(region) => region,
  61. None => {
  62. error!("Atlas does not contain fallback texture, will error out if missing textures exist");
  63. None
  64. }
  65. },
  66. banned: MeshFeatures::default(),
  67. // always require features present in the vertex format
  68. required: V::features()
  69. }
  70. }
  71. pub fn ban_feature(mut self, feature: MeshFeature) -> Self {
  72. self.banned |= feature;
  73. self
  74. }
  75. pub fn ban_features(mut self, features: MeshFeatures) -> Self {
  76. self.banned |= features;
  77. self
  78. }
  79. pub fn require_feature(mut self, feature: MeshFeature) -> Self {
  80. self.required |= feature;
  81. self
  82. }
  83. pub fn require_features(mut self, features: MeshFeatures) -> Self {
  84. self.required |= features;
  85. self
  86. }
  87. /// Extract vertices and indices from file contents
  88. /// If using wgpu you can use `create` to also upload it to the gpu
  89. pub fn read<V: Vertex>(&self, bytes: &[u8]) -> Result<(Vec<V>, Vec<Index>)> {
  90. let mut bytes = Cursor::new(bytes);
  91. let bytes = &mut bytes;
  92. let mut header = [0; 5];
  93. bytes.read_exact(&mut header)?;
  94. if &header != b"CHAIR" {
  95. return Err(Error::WrongHeader(header));
  96. }
  97. let version = bytes.read_u8()?;
  98. debug!("Mesh version is {version}");
  99. if version != 0 {
  100. return Err(Error::UnknownVersion(version));
  101. }
  102. let features = bytes.read_u8()?;
  103. // only safe since there are 8 features - none can be unused
  104. let features = unsafe {
  105. MeshFeatures::from_bits_unchecked(features)
  106. };
  107. debug!("Mesh features are {features:?}");
  108. let banned = features & self.banned;
  109. if !banned.is_empty() {
  110. return Err(Error::BannedFeatures(banned));
  111. }
  112. let missing = self.required & !features;
  113. if !missing.is_empty() {
  114. return Err(Error::MissingFeatures(missing));
  115. }
  116. let colours = if features.contains(MeshFeature::Coloured) {
  117. let len = bytes.read_u16::<LE>()?;
  118. debug!("Have {len} colours");
  119. (0..len)
  120. .map(|_| {
  121. Ok([chan(bytes)?, chan(bytes)?, chan(bytes)?, chan(bytes)?])
  122. })
  123. .collect::<Result<_>>()?
  124. } else {
  125. vec![]
  126. };
  127. let textures = if features.contains(MeshFeature::Textured) {
  128. let len = bytes.read_u8()?;
  129. debug!("Have {len} textures");
  130. (0..len)
  131. .map(|n| {
  132. let len = bytes.read_u8()?;
  133. let mut data = vec![0; len as usize];
  134. bytes.read_exact(&mut data)?;
  135. String::from_utf8(data)
  136. .map_err(|_| Error::InvalidTextureName(n))
  137. })
  138. .map(|name| match name {
  139. Ok(name) => match self.atlas.get(&name) {
  140. Some(region) => Ok(region),
  141. None => {
  142. warn!("Mesh uses missing texture {name}");
  143. if let Some(fallback) = self.fallback {
  144. Ok(fallback)
  145. } else {
  146. Err(Error::MissingTexture(name))
  147. }
  148. }
  149. },
  150. Err(e) => Err(e)
  151. })
  152. .collect::<Result<_>>()?
  153. } else {
  154. vec![]
  155. };
  156. let read_pos_comp = if features.contains(MeshFeature::ShortPos) {
  157. read_pos_short
  158. } else {
  159. read_pos_long
  160. };
  161. let read_col_index = if colours.len() > 255 {
  162. read_col_u16
  163. } else {
  164. read_col_u8
  165. };
  166. let read_normal = if features.contains(MeshFeature::ShortNormals) {
  167. read_normal_short
  168. } else {
  169. read_f32
  170. };
  171. let read_uv = if features.contains(MeshFeature::ShortUvs) {
  172. read_uv_short
  173. } else {
  174. read_f32
  175. };
  176. /* let skeleton = if features.contains(MeshFeature::Rigged) {
  177. // TODO: read skeleton
  178. let len = bytes.read_u8()?;
  179. (0..len)
  180. .map(|_| bytes.read_f32()?)
  181. .collect()
  182. } else {
  183. vec![]
  184. };
  185. let read_bone_indices = if skeleton.len() < 3 {
  186. || {
  187. let bits = bytes.read_u8()?;
  188. [
  189. (bits & 0b11) as u32,
  190. (bits & 0b0000_1100) as u32]
  191. }
  192. } else {
  193. || ()
  194. };*/
  195. // number of textured objects
  196. let object_count = bytes.read_u8()?;
  197. debug!("Have {object_count} objects");
  198. let vertices = (0..object_count)
  199. .flat_map(|n| {
  200. let vertex_count = bytes.read_u32::<LE>()?;
  201. debug!("Object {n} has {vertex_count} vertices");
  202. // allow going outside 0.0 to 1.0 range by mapping positions
  203. let (scale, offset) = if features.contains(MeshFeature::ShortPos) {
  204. // 0 to 128 precision as opposed to 0 to 255, which cannot be divided evenly
  205. // divided here for efficiency
  206. ([
  207. bytes.read_f32::<LE>()? / 128.0,
  208. bytes.read_f32::<LE>()? / 128.0,
  209. bytes.read_f32::<LE>()? / 128.0
  210. ], [
  211. bytes.read_f32::<LE>()?,
  212. bytes.read_f32::<LE>()?,
  213. bytes.read_f32::<LE>()?
  214. ])
  215. } else {
  216. ([1.0; 3], [0.0; 3])
  217. };
  218. debug!("Scale is {scale:?}, offset is {offset:?}");
  219. let region = if features.contains(MeshFeature::Textured) {
  220. textures.get(bytes.read_u8()? as usize)
  221. .ok_or_else(|| Error::UnknownTexture(n))?
  222. } else {
  223. &AtlasRegion {
  224. xy: [0.0; 2],
  225. x2y: [0.0; 2],
  226. x2y2: [0.0; 2],
  227. xy2: [0.0; 2]
  228. }
  229. };
  230. (0..vertex_count).map(|_| {
  231. let pos = [
  232. read_pos_comp(bytes, scale[0], offset[0])?,
  233. read_pos_comp(bytes, scale[1], offset[1])?,
  234. read_pos_comp(bytes, scale[2], offset[2])?
  235. ];
  236. let col = if features.contains(MeshFeature::Coloured) {
  237. let index = read_col_index(bytes)?;
  238. colours.get(index as usize).copied()
  239. .ok_or_else(|| Error::UnknownColour(index))?
  240. } else {
  241. [1.0; 4]
  242. };
  243. let normals = if features.contains(MeshFeature::Normals) {
  244. [
  245. read_normal(bytes)?,
  246. read_normal(bytes)?,
  247. read_normal(bytes)?
  248. ]
  249. } else {
  250. [0.0; 3]
  251. };
  252. let uvs = if features.contains(MeshFeature::Textured) {
  253. region.map_uvs(read_uv(bytes)?, read_uv(bytes)?)
  254. } else {
  255. [0.0; 2]
  256. };
  257. /* let (bones, weights) = if features.contains(MeshFeature::Rigged) {
  258. let bones = read_bone_indices()?;
  259. let weights = read_weights()?;
  260. (bones, weights)
  261. } else {
  262. ([0; 4], [0.0; 4]
  263. };*/
  264. Ok(V::new(pos, col, normals, uvs, /*bones, weights*/))
  265. }).collect::<Result<Vec<_>>>()
  266. })
  267. .flatten()
  268. .collect::<Vec<V>>();
  269. // use smallest index size that can hold all vertices
  270. let read_index = if vertices.len() > 65535 {
  271. read_index_u32
  272. } else if vertices.len() > 255 {
  273. read_index_u16
  274. } else {
  275. read_index_u8
  276. };
  277. let index_count = bytes.read_u32::<LE>()?;
  278. debug!("Have {index_count} indices");
  279. let indices = (0..index_count)
  280. .map(|_| read_index(bytes))
  281. .collect::<Result<_>>()?;
  282. Ok((vertices, indices))
  283. }
  284. /// Read and create a mesh on the GPU
  285. pub fn create<V: Vertex + std::fmt::Debug>(&self, device: &Device, bytes: &[u8]) -> Result<Mesh> {
  286. let (vertices, indices) = self.read::<V>(bytes)?;
  287. Ok(Mesh::new(device, &vertices, &indices))
  288. }
  289. }
  290. fn read_pos_short(bytes: &mut Cursor<&[u8]>, scale: f32, offset: f32) -> Result<f32> {
  291. Ok(bytes.read_u8()? as f32 * scale + offset)
  292. }
  293. fn read_pos_long(bytes: &mut Cursor<&[u8]>, _: f32, _: f32) -> Result<f32> {
  294. read_f32(bytes)
  295. }
  296. fn chan(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  297. Ok(bytes.read_u8()? as f32 / 255.0)
  298. }
  299. fn read_col_u8(bytes: &mut Cursor<&[u8]>) -> Result<u16> {
  300. Ok(bytes.read_u8()? as u16)
  301. }
  302. fn read_col_u16(bytes: &mut Cursor<&[u8]>) -> Result<u16> {
  303. Ok(bytes.read_u16::<LE>()?)
  304. }
  305. fn read_normal_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  306. Ok(NORMAL[bytes.read_u8()? as usize])
  307. }
  308. fn read_f32(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  309. Ok(bytes.read_f32::<LE>()?)
  310. }
  311. fn read_uv_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  312. // 128 instead of 255 to be able to evenly divide
  313. Ok(bytes.read_u8()? as f32 / 128.0)
  314. }
  315. fn read_index_u32(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
  316. Ok(bytes.read_u32::<LE>()?)
  317. }
  318. fn read_index_u16(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
  319. Ok(bytes.read_u16::<LE>()? as Index)
  320. }
  321. fn read_index_u8(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
  322. Ok(bytes.read_u8()? as Index)
  323. }
  324. const NORMAL: [f32; 256] = include!(concat!(env!("OUT_DIR"), "/normals.rs"));