1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
|
//! OBJ file format parsing.
//!
//! File format documentation: <https://paulbourke.net/dataformats/obj>
use std::path::PathBuf;
use crate::file_format::wavefront::common::{
keyword,
parse_statement_line,
ParsingError,
Triplet,
};
use crate::mesh::Mesh;
use crate::util::try_option;
use crate::vector::{Vec2, Vec3};
use crate::vertex::{Builder as VertexBuilder, Vertex};
/// Parses the content of a Wavefront `.obj`.
///
/// # Errors
/// Will return `Err` if the `.obj` content is formatted incorrectly.
pub fn parse(obj_content: &str) -> Result<Obj, Error>
{
let lines = obj_content
.lines()
.enumerate()
.map(|(line_index, line)| (line_index + 1, line));
let statements = lines
.map(|(line_no, line)| (line_no, parse_statement_line::<Keyword>(line, line_no)))
.filter_map(|(line_no, result)| {
let opt_statement = match result {
Ok(opt_statement) => opt_statement,
Err(err) => {
return Some(Err(err));
}
};
Some(Ok((line_no, opt_statement?)))
})
.collect::<Result<Vec<_>, _>>()?;
let vertex_positions = statements
.iter()
.filter_map(|(line_no, statement)| {
if statement.keyword != Keyword::V {
return None;
}
let x = try_option!(statement.get_float_arg(0, *line_no));
let y = try_option!(statement.get_float_arg(1, *line_no));
let z = try_option!(statement.get_float_arg(2, *line_no));
Some(Ok(Vec3 { x, y, z }))
})
.collect::<Result<Vec<_>, _>>()?;
let texture_positions = statements
.iter()
.filter_map(|(line_no, statement)| {
if statement.keyword != Keyword::Vt {
return None;
}
let u = try_option!(statement.get_float_arg(0, *line_no));
let v = try_option!(statement.get_float_arg(1, *line_no));
// let w = try_option!(statement.get_float_arg(2, *line_no));
Some(Ok(Vec2 { x: u, y: v }))
})
.collect::<Result<Vec<_>, _>>()?;
let vertex_normals = statements
.iter()
.filter_map(|(line_no, statement)| {
if statement.keyword != Keyword::Vn {
return None;
}
let i = try_option!(statement.get_float_arg(0, *line_no));
let j = try_option!(statement.get_float_arg(1, *line_no));
let k = try_option!(statement.get_float_arg(2, *line_no));
Some(Ok(Vec3 { x: i, y: j, z: k }))
})
.collect::<Result<Vec<_>, _>>()?;
let material_specifiers = statements
.iter()
.filter_map(|(line_no, statement)| {
if statement.keyword != Keyword::Usemtl {
return None;
}
let material_name = try_option!(statement.get_text_arg(0, *line_no));
Some(Ok(MaterialSpecifier {
material_name: material_name.to_string(),
line_no: *line_no,
}))
})
.collect::<Result<Vec<_>, _>>()?;
let faces = statements
.iter()
.filter_map(|(line_no, statement)| {
if statement.keyword != Keyword::F {
return None;
}
let vertex_a = try_option!(statement.get_triplet_arg(0, *line_no)).into();
let vertex_b = try_option!(statement.get_triplet_arg(1, *line_no)).into();
let vertex_c = try_option!(statement.get_triplet_arg(2, *line_no)).into();
let material_name =
find_material_specifier_for_line_no(&material_specifiers, *line_no)
.map(|material_specifier| material_specifier.material_name.clone());
Some(Ok(Face {
vertices: [vertex_a, vertex_b, vertex_c],
material_name,
}))
})
.collect::<Result<Vec<Face>, _>>()?;
let mtl_libs = statements
.iter()
.filter_map(|(line_no, statement)| {
if statement.keyword != Keyword::Mtllib {
return None;
}
let mtl_lib_paths = try_option!(statement
.arguments
.iter()
.enumerate()
.map(|(index, value)| Ok(PathBuf::from(value.to_text(index, *line_no)?)))
.collect::<Result<Vec<_>, ParsingError>>());
Some(Ok(mtl_lib_paths))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Obj {
vertex_positions,
vertex_normals,
texture_positions,
faces,
mtl_libs,
})
}
/// The output from parsing the content of a Wavefront `.obj` using [`parse`].
#[derive(Debug)]
#[non_exhaustive]
pub struct Obj
{
pub vertex_positions: Vec<Vec3<f32>>,
pub vertex_normals: Vec<Vec3<f32>>,
pub texture_positions: Vec<Vec2<f32>>,
pub faces: Vec<Face>,
pub mtl_libs: Vec<Vec<PathBuf>>,
}
impl Obj
{
pub fn to_mesh(&self) -> Result<Mesh, Error>
{
let vertices = self
.faces
.iter()
.map(|face| face.vertices.clone())
.flatten()
.map(|face_vertex| face_vertex.to_vertex(self))
.collect::<Result<Vec<_>, Error>>()?;
Ok(Mesh::new(
vertices,
Some(
self.faces
.iter()
.map(|face| face.vertices.clone())
.flatten()
.enumerate()
.map(|(index, _)| {
u32::try_from(index).map_err(|_| Error::FaceIndexTooBig(index))
})
.collect::<Result<Vec<_>, _>>()?,
),
))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Face
{
pub vertices: [FaceVertex; 3],
pub material_name: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FaceVertex
{
pub position: u32,
pub texture: Option<u32>,
pub normal: Option<u32>,
}
impl FaceVertex
{
/// Tries to convert this face vertex into a [`Vertex`].
pub fn to_vertex(&self, obj: &Obj) -> Result<Vertex, Error>
{
let vertex_pos = *obj.vertex_positions.get(self.position as usize - 1).ok_or(
Error::FaceVertexPositionNotFound { vertex_pos_index: self.position },
)?;
let face_vertex_texture =
self.texture.ok_or(Error::NoFaceVertexTextureNotSupported)?;
let texture_pos = *obj
.texture_positions
.get(face_vertex_texture as usize - 1)
.ok_or(Error::FaceTexturePositionNotFound {
texture_pos_index: face_vertex_texture,
})?;
let face_vertex_normal =
self.normal.ok_or(Error::NoFaceVertexNormalNotSupported)?;
let vertex_normal = *obj
.vertex_normals
.get(face_vertex_normal as usize - 1)
.ok_or(Error::FaceVertexNormalNotFound {
vertex_normal_index: face_vertex_normal,
})?;
Ok(VertexBuilder::new()
.pos(vertex_pos)
.texture_coords(texture_pos)
.normal(vertex_normal)
.build()
.unwrap())
}
}
impl From<Triplet> for FaceVertex
{
fn from(triplet: Triplet) -> Self
{
Self {
position: triplet.0,
texture: triplet.1,
normal: triplet.2,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error
{
#[error(transparent)]
ParsingError(#[from] ParsingError),
#[error(
"Face vertex position with index {vertex_pos_index} (1-based) was not found"
)]
FaceVertexPositionNotFound
{
vertex_pos_index: u32
},
#[error(
"Face texture position with index {texture_pos_index} (1-based) was not found"
)]
FaceTexturePositionNotFound
{
texture_pos_index: u32
},
#[error(
"Face vertex normal with index {vertex_normal_index} (1-based) was not found"
)]
FaceVertexNormalNotFound
{
vertex_normal_index: u32
},
#[error("Face index {0} is too big to fit into a 32-bit integer")]
FaceIndexTooBig(usize),
#[error("Face vertices without textures are not yet supported")]
NoFaceVertexTextureNotSupported,
#[error("Face vertices without normals are not yet supported")]
NoFaceVertexNormalNotSupported,
}
keyword! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Keyword {
#[keyword(rename = "v")]
V,
#[keyword(rename = "vn")]
Vn,
#[keyword(rename = "vt")]
Vt,
#[keyword(rename = "o")]
O,
#[keyword(rename = "s")]
S,
#[keyword(rename = "f")]
F,
#[keyword(rename = "mtllib")]
Mtllib,
#[keyword(rename = "usemtl")]
Usemtl,
}
}
#[derive(Debug)]
struct MaterialSpecifier
{
material_name: String,
line_no: usize,
}
fn find_material_specifier_for_line_no(
material_specifiers: &[MaterialSpecifier],
line_no: usize,
) -> Option<&MaterialSpecifier>
{
material_specifiers
.iter()
.rev()
.find(|material_specifier| material_specifier.line_no < line_no)
}
#[cfg(test)]
mod tests
{
use super::parse;
#[test]
fn parse_containing_usemtl_works()
{
let obj = parse(concat!(
"usemtl dark-green\n",
"f 6/8/1 7/5/3 1/3/2\n",
"f 1/2/4 4/1/8 3/4/2\n",
"usemtl light-pink\n",
"f 9/1/7 5/1/2 3/2/7"
))
.expect("Expected Ok");
assert_eq!(obj.faces.len(), 3);
assert_eq!(
obj.faces[0].material_name.as_ref().expect("Expected Some"),
"dark-green"
);
assert_eq!(
obj.faces[1].material_name.as_ref().expect("Expected Some"),
"dark-green"
);
assert_eq!(
obj.faces[2].material_name.as_ref().expect("Expected Some"),
"light-pink"
);
}
}
|