glcanvas/js/obj.js

63 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-09-21 01:15:41 -05:00
function parseObj(docStr) {
2024-09-27 21:41:08 -05:00
const bufPositions = [];
const bufNormals = [];
const out = [];
var vertCount = 0;
2024-09-21 01:15:41 -05:00
const ops = {
v(str) {
var xyz = str.match(/[0-9.-]+/g).map(Number);
2024-09-27 21:41:08 -05:00
bufPositions.push(xyz);
2024-09-21 01:15:41 -05:00
},
vn(str) {
var xyz = str.match(/[0-9.-]+/g).map(Number);
2024-09-27 21:41:08 -05:00
bufNormals.push(xyz);
2024-09-21 01:15:41 -05:00
},
f(str) {
2024-09-27 21:41:08 -05:00
const pts = [];
2024-09-21 01:15:41 -05:00
for (var faceStr of str.split(" ")) {
var [iV, iVt, iVn] = faceStr.split("/").map(Number);
/* obj uses 1-based indices */
iV--; iVt--; iVn--;
2024-09-27 21:41:08 -05:00
pts.push({
2024-09-21 01:15:41 -05:00
iV: iV,
// iVt: iVt,
iVn: iVn,
});
}
/* triangulate. */
2024-09-27 21:41:08 -05:00
for (var i = 0; i < pts.length - 2; i++) {
out.push(
bufPositions[pts[0].iV],
bufNormals[pts[0].iVn],
bufPositions[pts[i + 1].iV],
bufNormals[pts[i + 1].iVn],
bufPositions[pts[i + 2].iV],
bufNormals[pts[i + 2].iVn],
2024-09-21 01:15:41 -05:00
);
2024-09-27 21:41:08 -05:00
vertCount += 3;
2024-09-21 01:15:41 -05:00
}
}
};
for (var line of docStr.split("\n")) { /* if you use crlf that sucks lol */
if (line == "" || line.startsWith("#")) {
continue;
}
var tks = line.split(" ");
var op = tks.shift();
var cont = tks.join(" ");
var opFunc = ops[op];
if (opFunc) opFunc(cont);
}
2024-09-27 21:41:08 -05:00
return [new Float32Array(out.flat()), vertCount];
2024-09-21 01:15:41 -05:00
}