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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
use std::{collections::HashMap, result::Result};
use derive_more::{Constructor, From, Into};
use crate::{
get_on_off_from_str, get_token_float, get_token_int, get_token_string, tokenizer::Token,
};
use nom::{
branch::alt,
combinator::{map, opt},
multi::{fold_many0, fold_many1, many1},
sequence::{preceded, tuple},
IResult,
};
use thiserror::Error;
/// A wrapper for an underlying error which occurred
/// while parsing the token stream.
#[derive(Error, Debug)]
pub enum ModelError {
#[error("Parse Error: `{0}`")]
Parse(String),
}
/// Representation of vertex data. The w component is optional.
#[derive(Copy, Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Vertex {
/// X coordinate
pub x: f32,
/// Y coordinate
pub y: f32,
/// Z coordinate
pub z: f32,
/// Optional W coordinate
pub w: Option<f32>,
}
/// Representation of normal data.
#[derive(Copy, Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Normal {
/// X coordinate
pub x: f32,
/// Y coordinate
pub y: f32,
/// Z coordinate
pub z: f32,
}
/// Representation of texture data. v/w are optional.
#[derive(Copy, Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Texture {
/// U coordinate
pub u: f32,
/// Optional V coordinate
pub v: Option<f32>,
/// Optional W coordinate
pub w: Option<f32>,
}
/// Defines the settings that get applied to a group of faces.
#[derive(Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Group {
/// The name of the material to apply to the group.
pub material_name: String,
/// Bevel interpolation setting.
pub bevel: bool,
/// Color interpolation setting.
pub c_interp: bool,
/// Disolve interpolation setting.
pub d_interp: bool,
/// Level of detail setting.
pub lod: u8,
/// The name of the texture map file.
pub texture_map: Option<String>,
}
/// Holds the vertex/texture/normal indicies for a part of a face.
#[derive(Copy, Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct FaceElement {
/// Vertex index. Note that these START at 1, NOT 0.
pub vertex_index: i32,
/// Optional texture index. Note that these START at 1, NOT 0.
pub texture_index: Option<i32>,
/// Optional normal index. Note that these START at 1, NOT 0.
pub normal_index: Option<i32>,
}
/// The primary purpose is to store the collection of
/// elements (vertices/normals/texture coordinates) that
/// compose a face. This also contains a smoothing group
/// identifier, as specified by the obj file.
#[derive(Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Face {
/// Collection of `FaceElement`.
pub elements: Vec<FaceElement>,
/// The smoothing group identifier.
pub smoothing_group: i32,
}
/// Contains the indicies for a line element.
#[derive(Copy, Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct LineElement {
/// Vertex index. Note that these START at 1, NOT 0.
pub vertex_index: i32,
/// Optional texture index. Note that these START at 1, NOT 0.
pub texture_index: Option<i32>,
}
/// Contains the set of elements which compose a line.
#[derive(Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Line {
/// Set of line elements.
pub elements: Vec<LineElement>,
}
/// Contains a set of id's for the verticies which compose the point collection.
#[derive(Clone, Constructor, Debug, Default, From, Into, PartialEq)]
pub struct Point {
/// Set of vertex indices. Note that these START at 1, NOT 0.
pub elements: Vec<i32>,
}
/// This holds the end result of parsing an obj file.
/// The default group for all models is "default".
/// That is to say, if no group is defined in a file,
/// a "default" group will be used.
///
/// Everything will fall under the "default" group until another group
/// is specified.
#[derive(Clone, Debug, From, Into)]
pub struct Model {
/// Collection of vertex data
pub vertices: Vec<Vertex>,
// Collection of normal data
pub normals: Vec<Normal>,
/// Collection of texture coordinate data
pub textures: Vec<Texture>,
/// A map of group name to a collection of faces which belong to the group
/// Everything will fall under the "default" group until another group
/// is specified.
pub faces: HashMap<String, Vec<Face>>,
/// A map of group name to a collection of lines.
/// Everything will fall under the "default" group until another group
/// is specified.
pub lines: HashMap<String, Vec<Line>>,
/// A map of group name to a collection of points.
/// Everything will fall under the "default" group until another group
/// is specified.
pub points: HashMap<String, Vec<Point>>,
/// A map of group name to the groups specific data.
/// Everything will fall under the "default" group until another group
/// is specified.
pub groups: HashMap<String, Group>,
/// The material library files to use with this obj.
pub material_libs: Vec<String>,
/// The texture library files to use with this obj.
pub texture_libs: Vec<String>,
/// The file name for the shadow object
pub shadow_obj: Option<String>,
/// The file name for the ray trace object
pub trace_obj: Option<String>,
current_group: Vec<String>,
current_smoothing_group: i32,
}
impl Default for Model {
fn default() -> Self {
Self {
vertices: Default::default(),
normals: Default::default(),
textures: Default::default(),
faces: Default::default(),
lines: Default::default(),
points: Default::default(),
groups: {
let mut res = HashMap::new();
res.insert("default".into(), Default::default());
res
},
material_libs: Default::default(),
texture_libs: Default::default(),
shadow_obj: Default::default(),
trace_obj: Default::default(),
current_group: vec!["default".into()],
current_smoothing_group: 0,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum ModelElement {
Vertex(Vertex),
Normal(Normal),
Texture(Texture),
Face(Face),
Line(Line),
Point(Point),
Group(Vec<String>),
MaterialLib(Vec<String>),
Material(String),
ObjName(String),
Smoothing(i32),
Bevel(bool),
CInterp(bool),
DInterp(bool),
Lod(i32),
ShadowObj(String),
TraceObj(String),
TextureLib(Vec<String>),
TextureMap(String),
}
pub(crate) fn parse(input: &[Token]) -> Result<Model, ModelError> {
match fold_many0(
alt((
map(parse_vertex, ModelElement::Vertex),
map(parse_vertex_normal, ModelElement::Normal),
map(parse_vertex_texture, ModelElement::Texture),
map(parse_face, ModelElement::Face),
map(parse_line, ModelElement::Line),
map(parse_point, ModelElement::Point),
parse_mat_lib,
parse_material,
parse_obj_name,
parse_smoothing,
parse_bevel,
parse_c_interp,
parse_d_interp,
parse_lod,
parse_shadow_obj,
parse_trace_obj,
parse_texture_lib,
parse_texture_map,
parse_group,
)),
Model::default,
|mut model: Model, item: ModelElement| {
match item {
ModelElement::Vertex(x) => model.vertices.push(x),
ModelElement::Normal(n) => model.normals.push(n),
ModelElement::Texture(t) => model.textures.push(t),
ModelElement::Face(mut f) => {
f.smoothing_group = model.current_smoothing_group;
for g in &model.current_group {
let set = model.faces.entry(g.clone()).or_insert_with(Vec::new);
set.push(f.clone());
}
},
ModelElement::Line(l) => {
for g in &model.current_group {
let set = model.lines.entry(g.clone()).or_insert_with(Vec::new);
set.push(l.clone());
}
},
ModelElement::Point(p) => {
for g in &model.current_group {
let set = model.points.entry(g.clone()).or_insert_with(Vec::new);
set.push(p.clone());
}
},
ModelElement::Group(groups) => {
model.current_group.clear();
for g in groups {
model.groups.insert(g.clone(), Default::default());
model.current_group.push(g);
}
},
ModelElement::MaterialLib(libs) => model.material_libs.extend(libs),
ModelElement::Material(name) => {
for g in &model.current_group {
let group = model.groups.entry(g.clone()).or_default();
group.material_name = name.clone();
}
},
ModelElement::ObjName(_name) => {},
ModelElement::Smoothing(group_id) => {
model.current_smoothing_group = group_id;
},
ModelElement::Bevel(_flag) => {},
ModelElement::CInterp(_flag) => {},
ModelElement::DInterp(_flag) => {},
ModelElement::Lod(_level) => {},
ModelElement::ShadowObj(_name) => {},
ModelElement::TraceObj(_name) => {},
ModelElement::TextureLib(libs) => {
model.texture_libs.extend(libs);
},
ModelElement::TextureMap(name) => {
for g in &model.current_group {
let group = model.groups.entry(g.clone()).or_default();
group.texture_map = Some(name.clone());
}
},
}
model
},
)(input)
{
Ok((_, acc)) => Ok(acc),
Err(e) => Err(ModelError::Parse(e.to_string())),
}
}
pub(crate) fn parse_vertex(input: &[Token]) -> IResult<&[Token], Vertex> {
map(
preceded(
token_match!(Token::Vertex),
tuple((
token_match!(Token::Float(_) | Token::Int(_)),
token_match!(Token::Float(_) | Token::Int(_)),
token_match!(Token::Float(_) | Token::Int(_)),
opt(token_match!(Token::Float(_) | Token::Int(_))),
)),
),
|(x, y, z, w)| {
let (x, y, z) = (
match get_token_float(&x) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
match get_token_float(&y) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
match get_token_float(&z) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
);
let w = w.map(|val| match get_token_float(&val) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
});
(x, y, z, w).into()
},
)(input)
}
pub(crate) fn parse_vertex_normal(input: &[Token]) -> IResult<&[Token], Normal> {
map(
preceded(
token_match!(Token::VertexNormal),
tuple((
token_match!(Token::Float(_) | Token::Int(_)),
token_match!(Token::Float(_) | Token::Int(_)),
token_match!(Token::Float(_) | Token::Int(_)),
)),
),
|(x, y, z)| {
let (x, y, z) = (
match get_token_float(&x) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
match get_token_float(&y) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
match get_token_float(&z) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
);
(x, y, z).into()
},
)(input)
}
pub(crate) fn parse_vertex_texture(input: &[Token]) -> IResult<&[Token], Texture> {
map(
preceded(
token_match!(Token::VertexTexture),
tuple((
token_match!(Token::Float(_) | Token::Int(_)),
opt(token_match!(Token::Float(_) | Token::Int(_))),
opt(token_match!(Token::Float(_) | Token::Int(_))),
)),
),
|(u, v, w)| {
let u = match get_token_float(&u) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
let v = v.map(|val| match get_token_float(&val) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
});
let w = w.map(|val| match get_token_float(&val) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
});
(u, v, w).into()
},
)(input)
}
pub(crate) fn parse_face(input: &[Token]) -> IResult<&[Token], Face> {
preceded(
token_match!(Token::Face),
fold_many1(
map(
tuple((
token_match!(Token::Int(_)),
opt(preceded(
token_match!(Token::Slash),
opt(token_match!(Token::Int(_))),
)),
opt(preceded(
token_match!(Token::Slash),
opt(token_match!(Token::Int(_))),
)),
)),
|(v, t, n)| {
let v = match get_token_int(&v) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
let t = match t {
Some(t) => t.map(|tex| match get_token_int(&tex) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
}),
None => None,
};
let n = match n {
Some(n) => n.map(|norm| match get_token_int(&norm) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
}),
None => None,
};
(v, t, n).into()
},
),
Face::default,
|mut f: Face, item: FaceElement| {
f.elements.push(item);
f
},
),
)(input)
}
pub(crate) fn parse_line(input: &[Token]) -> IResult<&[Token], Line> {
preceded(
token_match!(Token::Line),
fold_many1(
map(
tuple((
token_match!(Token::Int(_)),
opt(preceded(
token_match!(Token::Slash),
opt(token_match!(Token::Int(_))),
)),
)),
|(v, t)| {
let v = match get_token_int(&v) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
let t = t.flatten().map(|tex| match get_token_int(&tex) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
});
(v, t).into()
},
),
Line::default,
|mut f: Line, item: LineElement| {
f.elements.push(item);
f
},
),
)(input)
}
pub(crate) fn parse_point(input: &[Token]) -> IResult<&[Token], Point> {
preceded(
token_match!(Token::Point),
fold_many1(
map(token_match!(Token::Int(_)), |v| match get_token_int(&v) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
}),
Point::default,
|mut f: Point, item: i32| {
f.elements.push(item);
f
},
),
)(input)
}
pub(crate) fn parse_group(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::Group),
many1(map(
token_match!(Token::String(_)),
|s| match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
)),
),
ModelElement::Group,
)(input)
}
pub(crate) fn parse_mat_lib(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::MaterialLib),
many1(map(
token_match!(Token::String(_)),
|s| match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
},
)),
),
ModelElement::MaterialLib,
)(input)
}
pub(crate) fn parse_material(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::UseMaterial),
token_match!(Token::String(_)),
),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::Material(res)
},
)(input)
}
pub(crate) fn parse_obj_name(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::Object),
token_match!(Token::String(_) | Token::Int(_)),
),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::ObjName(res)
},
)(input)
}
pub(crate) fn parse_smoothing(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::Smoothing),
alt((
token_match!(Token::Int(_)),
map(token_match!(Token::String(_)), |s| {
let val = match get_on_off_from_str(&s) {
Ok(v) => v,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
if !val {
Token::Int(0)
} else {
log::error!("Invalid smoothing value encountered. Setting default to 1.");
Token::Int(1)
}
}),
)),
),
|s| {
let res = match get_token_int(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::Smoothing(res)
},
)(input)
}
pub(crate) fn parse_bevel(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(token_match!(Token::Bevel), token_match!(Token::String(_))),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
if let Ok(flag) = res.parse::<bool>() {
ModelElement::Bevel(flag)
} else {
ModelElement::Bevel(false)
}
},
)(input)
}
pub(crate) fn parse_c_interp(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(token_match!(Token::CInterp), token_match!(Token::String(_))),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
if let Ok(flag) = res.parse::<bool>() {
ModelElement::CInterp(flag)
} else {
ModelElement::CInterp(false)
}
},
)(input)
}
pub(crate) fn parse_d_interp(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(token_match!(Token::DInterp), token_match!(Token::String(_))),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
if let Ok(flag) = res.parse::<bool>() {
ModelElement::DInterp(flag)
} else {
ModelElement::DInterp(false)
}
},
)(input)
}
pub(crate) fn parse_lod(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(token_match!(Token::Lod), token_match!(Token::Int(_))),
|s| {
let res = match get_token_int(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::Lod(res)
},
)(input)
}
pub(crate) fn parse_shadow_obj(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::ShadowObj),
token_match!(Token::String(_)),
),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::ShadowObj(res)
},
)(input)
}
pub(crate) fn parse_trace_obj(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::TraceObj),
token_match!(Token::String(_)),
),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::TraceObj(res)
},
)(input)
}
pub(crate) fn parse_texture_lib(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::TextureMapLib),
many1(map(token_match!(Token::String(_)), |s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
res
})),
),
ModelElement::TextureLib,
)(input)
}
pub(crate) fn parse_texture_map(input: &[Token]) -> IResult<&[Token], ModelElement> {
map(
preceded(
token_match!(Token::UseTextureMap),
token_match!(Token::String(_)),
),
|s| {
let res = match get_token_string(&s) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
Default::default()
},
};
ModelElement::TextureMap(res)
},
)(input)
}