| 230 | } |
| 231 | |
| 232 | bool STLParser::parse_binary(const std::string& filename) { |
| 233 | std::ifstream fin(filename.c_str()); |
| 234 | if (!fin.is_open()) { |
| 235 | std::stringstream err_msg; |
| 236 | err_msg << "failed to open file \"" << filename << "\""; |
| 237 | throw IOError(err_msg.str()); |
| 238 | } |
| 239 | |
| 240 | const size_t FLOAT_SIZE = sizeof(float); |
| 241 | assert(FLOAT_SIZE == 4); |
| 242 | const size_t LINE_SIZE=256; |
| 243 | char buf[LINE_SIZE]; |
| 244 | |
| 245 | // 80 bytes header, no data significance. |
| 246 | fin.read(buf, 80); |
| 247 | if (!fin.good()) { |
| 248 | throw IOError("Unable to parse STL header."); |
| 249 | } |
| 250 | |
| 251 | fin.read(buf, 4); |
| 252 | const size_t num_faces = *reinterpret_cast<unsigned int*>(buf); |
| 253 | if (!fin.good()) { |
| 254 | throw IOError("Unable to parse STL number of faces."); |
| 255 | } |
| 256 | |
| 257 | for (size_t i=0; i<num_faces; i++) { |
| 258 | // Parse normal |
| 259 | fin.read(buf, FLOAT_SIZE*3); |
| 260 | const float nx = *reinterpret_cast<float*>(buf); |
| 261 | const float ny = *reinterpret_cast<float*>(buf + FLOAT_SIZE); |
| 262 | const float nz = *reinterpret_cast<float*>(buf + FLOAT_SIZE * 2); |
| 263 | assert(fin.good()); |
| 264 | |
| 265 | // vertex 1 |
| 266 | fin.read(buf, FLOAT_SIZE*3); |
| 267 | const float v1x = *reinterpret_cast<float*>(buf); |
| 268 | const float v1y = *reinterpret_cast<float*>(buf + FLOAT_SIZE); |
| 269 | const float v1z = *reinterpret_cast<float*>(buf + FLOAT_SIZE * 2); |
| 270 | assert(fin.good()); |
| 271 | |
| 272 | // vertex 2 |
| 273 | fin.read(buf, FLOAT_SIZE*3); |
| 274 | const float v2x = *reinterpret_cast<float*>(buf); |
| 275 | const float v2y = *reinterpret_cast<float*>(buf + FLOAT_SIZE); |
| 276 | const float v2z = *reinterpret_cast<float*>(buf + FLOAT_SIZE * 2); |
| 277 | assert(fin.good()); |
| 278 | |
| 279 | // vertex 3 |
| 280 | fin.read(buf, FLOAT_SIZE*3); |
| 281 | const float v3x = *reinterpret_cast<float*>(buf); |
| 282 | const float v3y = *reinterpret_cast<float*>(buf + FLOAT_SIZE); |
| 283 | const float v3z = *reinterpret_cast<float*>(buf + FLOAT_SIZE * 2); |
| 284 | assert(fin.good()); |
| 285 | |
| 286 | // attribute (2 bytes), not sure what purpose they serve. |
| 287 | fin.read(buf, 2); |
| 288 | |
| 289 | m_facet_normals.emplace_back(nx, ny, nz); |