-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconvert2.js
108 lines (104 loc) · 2.93 KB
/
convert2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"use strict";
exports.__esModule = true;
var OBJFile = require('obj-file-parser');
var fs = require("fs");
var path = require("path");
var obj = fs.readFileSync("./model.obj").toString();
var mtlRaw = fs.readFileSync("./model.mtl").toString('utf8');
function parseMTL(mtl) {
var output = {};
mtl.split('newmtl ').slice(1).forEach(function (block) {
var lines = block.split('\n');
var label = lines[0];
var props = {};
lines.slice(1).forEach(function (line) {
// Skip illum lines
if (line.indexOf('illum') === 0) {
return;
}
var toks = line.split(/\s+/);
var label = toks[0];
var data = toks.slice(1);
if (data.length === 1) {
props[label] = +data[0];
}
else {
props[label] = data.map(function (x) {
return Math.sqrt(x).toPrecision(4);
});
}
});
output[label] = props;
});
return output;
}
var mtl = parseMTL(mtlRaw);
var objF = new OBJFile(obj);
var data = objF.parse(objF);
var outpath = path.join(__dirname, 'model.json');
var output = {
positions: [],
chunks: []
};
/*
type colorValue = number; // 0-255
type positionId = number; // Index of that position
type CoordVal = number;
type Position = [CoordVal, CoordVal, CoordVal];
type Face = [positionId, positionId, positionId];
export type EfficientModel = {
positions: Array<Position>;
chunks: Array<{
color: [colorValue, colorValue, colorValue];
faces: Array<Face>;
}>;
}
*/
var VI = 'vertexIndex';
var model = data.models[0];
model.vertices.forEach(function (v) {
output.positions.push([sub(v.x), sub(v.y), sub(v.z)]);
});
function sub(coord) {
return coord - 4.5;
}
var _loop_1 = function (mtlKey) {
var m = mtl[mtlKey];
if (!m.Ka) {
console.log('PROBLEM with ' + mtlKey);
console.dir(m);
}
else {
var color_1 = m.Ka.map(function (c, i) {
return (255 * c) | 0;
});
m.Kd.forEach(function (c, i) {
if (color_1[i] === 0) {
color_1[i] = (255 * c) | 0;
}
});
var chunk_1 = {
color: color_1,
faces: []
};
model.faces.forEach(function (f) {
// Only if this face matches the material!
if (f.material === mtlKey) {
chunk_1.faces.push([
f.vertices[0][VI] - 1,
f.vertices[1][VI] - 1,
f.vertices[2][VI] - 1,
]);
console.log('we pushed some faces, eh?', chunk_1.faces);
}
else {
console.log("I guess " + f.material + " !== " + mtlKey);
}
});
output.chunks.push(chunk_1);
}
};
for (var mtlKey in mtl) {
_loop_1(mtlKey);
}
fs.writeFileSync(outpath, JSON.stringify(output, null, 2));