aboutsummaryrefslogtreecommitdiff
path: root/src/hittable/model.rs
blob: 1a652beeee26d55e47a3039c8830dfe005431bd6 (plain)
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
use std::sync::Arc;
use std::vec::Vec;

use crate::{hittable::{HitRecord, Hittable, AABB, HittableList, Triangle}, material::Material, ray::Ray, vec3::{Point3, Vec3}};

pub struct Model {
    faces: HittableList,
}

impl Model {
    fn parse_face_triplet(triplet: &str) -> Option<(isize, Option<isize>, Option<isize>)> {
        let mut triplet_iter = triplet.split("/");
        Some((triplet_iter.next()?.parse::<isize>().ok()?, triplet_iter.next().and_then(|val| val.parse::<isize>().ok()) , triplet_iter.next().and_then(|val| val.parse::<isize>().ok())))
    }
    pub fn from_obj(obj_data: &str, material: Arc<dyn Material>) -> Self {
        let mut geometric_vertices: Vec<Vec3> = Vec::new();
        let mut texture_vertices: Vec<(f64, f64)> = Vec::new();
        let mut vertex_normals: Vec<Vec3> = Vec::new();
        // no free-form objects, so no parameter-space vertices!
        let mut faces: Vec<Arc<dyn Hittable>> = Vec::new();
        for entry in obj_data.lines() {
            if entry.starts_with("#") {
                // comment
                continue;
            }
            let mut entry_iter = entry.split(' ');
            let operator = match entry_iter.next() {
                None => continue,
                Some(val) => val,
            };
            match operator {
                "v" | "vn" => {
                    let x = match entry_iter.next() {
                        None => {
                            eprintln!("Malformed {} entry in OBJ: Missing x!", operator);
                            continue;
                        },
                        Some(val) => {
                            match val.parse::<f64>() {
                                Err(_) => {
                                    eprintln!("Malformed {} entry in OBJ: Malformed f64 x!", operator);
                                    continue;
                                },
                                Ok(val) => val,
                            }
                        }
                    };
                    let y = match entry_iter.next() {
                        None => {
                            eprintln!("Malformed {} entry in OBJ: Missing y!", operator);
                            continue;
                        },
                        Some(val) => {
                            match val.parse::<f64>() {
                                Err(_) => {
                                    eprintln!("Malformed {} entry in OBJ: Malformed f64 y!", operator);
                                    continue;
                                },
                                Ok(val) => val,
                            }
                        }
                    };
                    let z = match entry_iter.next() {
                        None => {
                            eprintln!("Malformed {} entry in OBJ: Missing z!", operator);
                            continue;
                        },
                        Some(val) => {
                            match val.parse::<f64>() {
                                Err(_) => {
                                    eprintln!("Malformed {} entry in OBJ: Malformed f64 z!", operator);
                                    continue;
                                },
                                Ok(val) => val,
                            }
                        }
                    };
                    // who cares about w
                    match operator {
                        "v" => geometric_vertices.push(Vec3 {x, y, z}),
                        "vn" => vertex_normals.push(Vec3 {x, y, z}),
                        _ => panic!(),
                    }
                },
                "vt" => {
                    let u = match entry_iter.next() {
                        None => {
                            eprintln!("Malformed vt entry in OBJ: Missing u!");
                            continue;
                        },
                        Some(val) => {
                            match val.parse::<f64>() {
                                Err(_) => {
                                    eprintln!("Malformed vt entry in OBJ: Malformed f64 u!");
                                    continue;
                                },
                                Ok(val) => val,
                            }
                        }
                    };
                    let v = match entry_iter.next() {
                        None => {
                            eprintln!("Malformed vt entry in OBJ: Missing v!");
                            continue;
                        },
                        Some(val) => {
                            match val.parse::<f64>() {
                                Err(_) => {
                                    eprintln!("Malformed v entry in OBJ: Malformed f64 v!");
                                    continue;
                                },
                                Ok(val) => val,
                            }
                        }
                    };
                    // who cares about w
                    texture_vertices.push((u, v));
                },
                "f" => {
                    let mut triplets : Vec<(isize, Option<isize>, Option<isize>)> = Vec::new();
                    for triplet in entry_iter {
                        match Self::parse_face_triplet(triplet) {
                            None => {
                                eprintln!("Encountered malformed triplet in f operator!");
                            },
                            Some(val) => {
                                triplets.push(val);
                            }
                        };
                    }
                    // only support faces with *exactly* three vertices. yeah, i know.
                    if triplets.len() != 3 {
                        eprintln!("Encountered face with unsupported vertex count!");
                        continue;
                    }
                    let mut v0_index = triplets.get(0).unwrap().0;
                    if v0_index < 0 {
                        v0_index = geometric_vertices.len() as isize + v0_index;
                    } else {
                        v0_index = v0_index - 1;
                    }
                    let mut v1_index = triplets.get(1).unwrap().0;
                    if v1_index < 0 {
                        v1_index = geometric_vertices.len() as isize + v1_index;
                    } else {
                        v1_index = v1_index - 1;
                    }
                    let mut v2_index = triplets.get(2).unwrap().0;
                    if v2_index < 0 {
                        v2_index = geometric_vertices.len() as isize + v2_index;
                    } else {
                        v2_index = v2_index - 1;
                    }
                    let mut triangle = Triangle {
                        v0: geometric_vertices.get(v0_index as usize).unwrap().clone(),
                        v1: geometric_vertices.get(v1_index as usize).unwrap().clone(),
                        v2: geometric_vertices.get(v2_index as usize).unwrap().clone(),
                        material: material.clone(),
                        custom_normal: None,
                    };
                    if let Some(vn0) = triplets.get(0).unwrap().2 {
                        if let Some(vn1) = triplets.get(1).unwrap().2 {
                            if let Some(vn2) = triplets.get(2).unwrap().2 {
                                if vn0 != vn1 || vn1 != vn2 {
                                    eprintln!("Unsupported geometry in OBJ file: Multiple normals for face!");
                                    continue
                                }
                                let mut vn0 = vn0;
                                if vn0 < 0 {
                                    vn0 = vertex_normals.len() as isize + v0_index;
                                } else {
                                    vn0 = vn0 - 1;
                                }
                                triangle.custom_normal = Some(vertex_normals.get(vn0 as usize).unwrap().unit_vector());
                            }
                        }
                    }
                    faces.push(Arc::new(triangle));
                },
                _ => {
                    eprintln!("Ignoring unknown operator {} in OBJ!", operator);
                    continue;
                },
            }
        }
        Self {
            faces: HittableList { objects: faces },
        }
    }
}

impl Hittable for Model {
    fn hit(&self, ray: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> {
        self.faces.hit(ray, t_min, t_max)
    }

    fn bounding_box(&self, time_start: f64, time_end: f64) -> Option<AABB> {
        self.faces.bounding_box(time_start, time_end)
    }
}