Last active
August 29, 2015 14:01
-
-
Save mortennobel/c89e082e70deac09550a to your computer and use it in GitHub Desktop.
Simple Obj File Loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Morten Nobel-Jørgensen on 06/05/14. | |
// Copyright (c) 2014 Morten Nobel-Joergensen. All rights reserved. | |
// | |
#include "ObjFile.h" | |
#include <fstream> | |
#include <sstream> | |
using namespace std; | |
using namespace glm; | |
bool ObjFile::save(std::string filename, std::vector<glm::dvec3> &positions, std::vector<int> &indices) { | |
std::ofstream os(filename.c_str()); | |
if(os.bad()) | |
return false; | |
for(int i=0;i<positions.size();i++){ | |
glm::dvec3 p = positions[i]; | |
os << "v "<< p[0] << " " << p[1] << " " << p[2] << "\n"; | |
} | |
for(int i=0;i<indices.size();){ | |
os << "f "; | |
for(size_t j = 0; j < 3 ; j++, i++){ | |
os << (indices[i]+1) << " "; | |
} | |
os<<std::endl; | |
} | |
os.close(); | |
return true; | |
} | |
bool ObjFile::load(std::string filename, std::vector<glm::dvec3> &positions, std::vector<int> &indices) { | |
ifstream os(filename.c_str()); | |
if(os.bad()) | |
return false; | |
positions.clear(); | |
indices.clear(); | |
const int c = 256; | |
char line[c]; | |
while (!os.eof()){ | |
os.getline(line, c); | |
if (strlen(line)==0){ | |
continue; | |
} | |
stringstream ss{line}; | |
string token; | |
ss >> token; | |
if (token=="v"){ | |
glm::dvec3 v; | |
ss >> v.x >> v.y >> v.z; | |
positions.push_back(v); | |
} | |
else if (token=="f"){ | |
int index; | |
for (int i=0;i<3;i++){ // assume only triangles | |
ss >> index; | |
indices.push_back(index-1); | |
} | |
} | |
} | |
os.close(); | |
return true; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Morten Nobel-Jørgensen on 06/05/14. | |
// Copyright (c) 2014 Morten Nobel-Joergensen. All rights reserved. | |
// | |
#pragma once | |
#include <glm/glm.hpp> | |
#include <vector> | |
#include <string> | |
class ObjFile { | |
public: | |
static bool save(std::string filename, std::vector<glm::dvec3> &positions, std::vector<int> &indices); | |
static bool load(std::string filename, std::vector<glm::dvec3> &positions, std::vector<int> &indices); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment