Reading OBJ files in MATLAB

% Not the most exciting code that I've written recently.
% Can you tell that it's finals week and I'm a little busy?

% readobj
% Reads the obj file format.
function [v, vt, vn, f] = readobj(filename)

fid = fopen(filename, 'r');

vcount = 0;
vtcount = 0;
vncount = 0;
fcount = 0;

v = [];
vt = [];
vn = [];
f = [];

% Iterate through each line of the OBJ file.
while ~feof(fid)

    line = fgets(fid);

    % Scan the file for vertices
    if line(1:2) == 'v '
        vcount = vcount + 1;
        v(vcount, :) = sscanf(line(3:end), '%f');

    % Scan the file for texture coordinates
    elseif line(1:3) == 'vt '
        vtcount = vtcount + 1;
        vt(vtcount, :) = sscanf(line(4:end), '%f');

    % Scan the file for normals
    elseif line(1:3) == 'vn '
        vncount = vncount + 1;
        vn(vncount, :) = sscanf(line(4:end), '%f');

    % Scan the file for face definitions
    elseif line(1:2) == 'f '
        fcount = fcount + 1;
        f(fcount, :) = sscanf(line(3:end), '%d/%d');
    end

end

disp(sprintf('Vertex count: %d', vcount))
disp(sprintf('Vertex texture count: %d', vtcount))
disp(sprintf('Vertex normal count: %d', vncount))
disp(sprintf('Face count: %d', fcount))

fclose(fid);

  1. jcchurch posted this