Reading an OBJ File

Complex 3D figures are usually drawn using 3D modeler software such as Blender. Here we shall briefly explain how to export 3D figure data to WebGL.

Let's draw a cube with one side colored in blue. Launch Blender. You will see a cube.

Changing the color of one side of a cube.

Step 1: Change the object interaction mode to 'Edit Mode'.

Step 2: Click 'Face select'.

Step 3: Click 'Rendered' for Viewport Shading.

Step 4: Click on the top face of the cube.

Step 5: Click 'Material Properties'.

Step 6: Click + to add a new material slot, then click 'New'.

Step 7: Change the name of the material to 'top'.

Step 8: Change the 'Base Color' to blue.

Step 9: Click 'Assign'.

Step 10: Go to File and export the project to a Wavefront (cube.obj) file. You will obtain two files: cube.obj and cube.mtl. The documentation for these two file formats can be found here and here.



cube.obj
# Blender v2.93.6 OBJ File: ''
# www.blender.org
mtllib cube.mtl
o Cube
v 1.000000 1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 1.000000 1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 -1.000000
v -1.000000 -1.000000 -1.000000
v -1.000000 1.000000 1.000000
v -1.000000 -1.000000 1.000000
vt 0.375000 0.750000
vt 0.625000 0.750000
vt 0.625000 1.000000
vt 0.375000 1.000000
vt 0.375000 0.000000
vt 0.625000 0.000000
vt 0.625000 0.250000
vt 0.375000 0.250000
vt 0.125000 0.500000
vt 0.375000 0.500000
vt 0.125000 0.750000
vt 0.625000 0.500000
vt 0.875000 0.500000
vt 0.875000 0.750000
vn 0.0000 0.0000 1.0000
vn -1.0000 0.0000 0.0000
vn 0.0000 -1.0000 0.0000
vn 1.0000 0.0000 0.0000
vn 0.0000 0.0000 -1.0000
vn 0.0000 1.0000 0.0000
usemtl Material
s off
f 4/1/1 3/2/1 7/3/1 8/4/1
f 8/5/2 7/6/2 5/7/2 6/8/2
f 6/9/3 2/10/3 4/1/3 8/11/3
f 2/10/4 1/12/4 3/2/4 4/1/4
f 6/8/5 5/7/5 1/12/5 2/10/5
usemtl top
f 1/12/6 5/13/6 7/14/6 3/2/6
cube.mtl
# Blender MTL File: 'None'
# Material Count: 2

newmtl Material
Ns 323.999994
Ka 1.000000 1.000000 1.000000
Kd 0.800000 0.800000 0.800000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.450000
d 1.000000
illum 2

newmtl top
Ns 225.000000
Ka 1.000000 1.000000 1.000000
Kd 0.000000 0.034110 0.800000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.450000
d 1.000000
illum 2

To retrieve these files over the internet, pass these filenames to AJAX calls. Generic functions should be created to translate the data so that they can be passed into buffer objects. Use the JavaScript split('\n') function to separate the lines. Among the useful generic parsing functions are:
StringParser.init(str)
StringParser.getWord()
StringParser.skipToNextWord()
StringParser.getInt()
StringParser.getFloat().