Java: OBJ to OpenGL ES Vertex Array Buffer

Posted on

This small java program will take an OBJ file, and convert it into a vertex Array and UV Array, ready to be used with OpenGL ES.

It’s very raw, user un-friendly, and is hardcoded to limit at 100 vertices. But works for me, so feel free to use.

//

// Code to parse a Wavefront OBJ file into a vertex map

//

import java.io.*;
import java.util.Scanner;

class ParseOBJ {
public static void main(String args[]) throws IOException {
//Initialise arrays for vertices, vertex textures, faces
float[][] vertexes = new float[100][3];
float[][] textures = new float[100][2];
String[][] faces = new String[100][3];

int vertpos = 0;
int textpos = 0;
int facepos = 0;

// Code to open the actual file here
Scanner s = new Scanner(System.in);

File f = new File(“d10.obj”);
Scanner numScan = new Scanner(f);

String line;
String vertexOutput = “”;
String textureOutput = “”;

while (numScan.hasNext())
{
line = numScan.nextLine();
if (line.startsWith(“v ”)) {
//This is the vertex array
String[] vertexSplit=line.split(“ ”);
vertexes[vertpos][0] = Float.valueOf(vertexSplit[1]);
vertexes[vertpos][1] = Float.valueOf(vertexSplit[2]);
vertexes[vertpos][2] = Float.valueOf(vertexSplit[3]);
vertpos++;
}
if (line.startsWith(“vt ”)) {
//This is the vertex texture array
String[] vertexSplit=line.split(“ ”);
textures[textpos][0] = Float.valueOf(vertexSplit[1]);
textures[textpos][1] = Float.valueOf(vertexSplit[2]);
textpos++;
}
if (line.startsWith(“f ”)) {
//This is the face array
String[] vertexSplit=line.split(“ ”);
faces[facepos][0] = vertexSplit[1];
faces[facepos][1] = vertexSplit[2];
faces[facepos][2] = vertexSplit[3];
facepos++;
}
}

// Code to convert face array into final texture array and vertex array
// Vertices first
for (int i = 0; i < facepos; i++) {
for (int j = 0; j < 3; j++) {
String[] removeslashes = faces[i][j].split(“/”);
int vertindex = Integer.parseInt(removeslashes[0]) – 1;
int textindex = Integer.parseInt(removeslashes[1]) – 1;
vertexOutput = vertexOutput + vertexes[vertindex][0] + “f, ” + vertexes[vertindex][1] + “f, ” + vertexes[vertindex][2] + “f, n”;
textureOutput = textureOutput + textures[textindex][0] + “f, ” + textures[textindex][1] + “f, n”;
}
}

System.out.println(“Vertex Data: n” + vertexOutput);
System.out.println(“Texture Data: n” + textureOutput);
}
}