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
|
//! MTL file format parsing.
//!
//! File format documentation: <https://paulbourke.net/dataformats/mtl>
use std::path::Path;
use crate::color::Color;
use crate::file_format::wavefront::common::{
keyword,
parse_statement_line,
ParsingError,
Statement,
};
use crate::material::{Builder as MaterialBuilder, Material};
use crate::texture::{Error as TextureError, Texture};
/// Parses the content of a Wavefront `.mtl`.
///
/// # Errors
/// Will return `Err` if the `.mtl` content is formatted incorrectly.
pub fn parse(obj_content: &str) -> Result<Vec<NamedMaterial>, 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 material_cnt = statements
.iter()
.filter(|(_, statement)| matches!(statement.keyword, Keyword::Newmtl))
.count();
tracing::debug!("Material count: {material_cnt}");
statements_to_materials(statements, material_cnt)
}
#[derive(Debug, Clone)]
pub struct NamedMaterial
{
pub name: String,
pub material: Material,
}
#[derive(Debug, Clone)]
pub struct UnfinishedNamedMaterial
{
name: String,
material_builder: MaterialBuilder,
ready: bool,
}
#[derive(Debug, thiserror::Error)]
pub enum Error
{
#[error(transparent)]
ParsingError(#[from] ParsingError),
#[error("Failed to open texture")]
TextureError(#[from] TextureError),
#[error(
"Unsupported number of arguments ({arg_count}) to {keyword} at line {line_no}"
)]
UnsupportedArgumentCount
{
keyword: String,
arg_count: usize,
line_no: usize,
},
#[error("Invalid number of arguments ({arg_count}) to {keyword} at line {line_no}")]
InvalidArgumentCount
{
keyword: String,
arg_count: usize,
line_no: usize,
},
}
#[tracing::instrument(skip_all)]
fn statements_to_materials(
statements: impl IntoIterator<Item = (usize, Statement<Keyword>)>,
material_cnt: usize,
) -> Result<Vec<NamedMaterial>, Error>
{
let mut materials = Vec::<NamedMaterial>::with_capacity(material_cnt);
let mut curr_material = UnfinishedNamedMaterial {
name: String::new(),
material_builder: MaterialBuilder::new(),
ready: false,
};
for (line_no, statement) in statements {
if statement.keyword == Keyword::Newmtl {
if curr_material.ready {
tracing::debug!("Building material");
let material = curr_material.material_builder.clone().build();
materials.push(NamedMaterial { name: curr_material.name, material });
}
let name = statement.get_text_arg(0, line_no)?;
curr_material.name = name.to_string();
curr_material.ready = true;
continue;
}
if !curr_material.ready {
// Discard statements not belonging to a material
continue;
};
match statement.keyword {
Keyword::Ka => {
let color = get_color_from_statement(&statement, line_no)?;
tracing::debug!("Adding ambient color");
curr_material.material_builder =
curr_material.material_builder.ambient(color);
}
Keyword::Kd => {
let color = get_color_from_statement(&statement, line_no)?;
tracing::debug!("Adding diffuse color");
curr_material.material_builder =
curr_material.material_builder.diffuse(color);
}
Keyword::Ks => {
let color = get_color_from_statement(&statement, line_no)?;
tracing::debug!("Adding specular color");
curr_material.material_builder =
curr_material.material_builder.specular(color);
}
Keyword::MapKa => {
if statement.arguments.len() > 1 {
return Err(Error::UnsupportedArgumentCount {
keyword: statement.keyword.to_string(),
arg_count: statement.arguments.len(),
line_no,
});
}
let texture_file_path = statement.get_text_arg(0, line_no)?;
let texture = Texture::open(Path::new(texture_file_path))?;
tracing::debug!("Adding ambient map");
let texture_id = texture.id();
curr_material.material_builder = curr_material
.material_builder
.texture(texture)
.ambient_map(texture_id);
}
Keyword::MapKd => {
let texture = get_map_from_texture(&statement, line_no)?;
tracing::debug!("Adding diffuse map");
let texture_id = texture.id();
curr_material.material_builder = curr_material
.material_builder
.texture(texture)
.diffuse_map(texture_id);
}
Keyword::MapKs => {
let texture = get_map_from_texture(&statement, line_no)?;
tracing::debug!("Adding specular map");
let texture_id = texture.id();
curr_material.material_builder = curr_material
.material_builder
.texture(texture)
.specular_map(texture_id);
}
Keyword::Newmtl => {}
}
}
if curr_material.ready {
tracing::debug!("Building last material");
let material = curr_material.material_builder.build();
materials.push(NamedMaterial { name: curr_material.name, material });
}
Ok(materials)
}
fn get_color_from_statement(
statement: &Statement<Keyword>,
line_no: usize,
) -> Result<Color<f32>, Error>
{
if statement.arguments.len() > 3 {
return Err(Error::InvalidArgumentCount {
keyword: statement.keyword.to_string(),
arg_count: statement.arguments.len(),
line_no,
});
}
let red = statement.get_float_arg(0, line_no)?;
let green = statement.get_float_arg(1, line_no)?;
let blue = statement.get_float_arg(2, line_no)?;
Ok(Color { red, green, blue })
}
fn get_map_from_texture(
statement: &Statement<Keyword>,
line_no: usize,
) -> Result<Texture, Error>
{
if statement.arguments.len() > 1 {
return Err(Error::UnsupportedArgumentCount {
keyword: statement.keyword.to_string(),
arg_count: statement.arguments.len(),
line_no,
});
}
let texture_file_path = statement.get_text_arg(0, line_no)?;
Ok(Texture::open(Path::new(texture_file_path))?)
}
keyword! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Keyword {
#[keyword(rename = "newmtl")]
Newmtl,
Ka,
Kd,
Ks,
#[keyword(rename = "map_Ka")]
MapKa,
#[keyword(rename = "map_Kd")]
MapKd,
#[keyword(rename = "map_Ks")]
MapKs,
}
}
|