-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
convert.js
423 lines (382 loc) · 13.4 KB
/
convert.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
const fs = require('fs').promises;
const { strict: assert } = require('assert');
const OBJFile = require('obj-file-parser');
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const prettier = require('prettier');
const { parse } = require('svg-parser');
/**
* Parse a material settings file. Each material is returned as a
* separate entry.
*
* @param {string} mtl - The contents of a material settings file.
* @returns A map of material names to properties.
*/
function parseMTL(mtl) {
const output = {};
mtl
.split('newmtl ')
.slice(1)
.forEach(function (block) {
const lines = block.split('\n');
const label = lines[0];
const props = {};
lines.slice(1).forEach(function (line) {
// Skip illum lines
if (line.indexOf('illum') === 0) {
return;
}
const toks = line.split(/\s+/u);
const lineLabel = toks[0];
const data = toks.slice(1);
if (data.length === 1) {
props[lineLabel] = Number(data[0]);
} else {
props[lineLabel] = data.map(function (x) {
return Math.sqrt(x).toPrecision(4);
});
}
});
output[label] = props;
});
return output;
}
/**
* This is a list of simple and distinct colors. These are used to help identify chunks of the
* model.
*
* These were taken from this blog post: https://sashamaps.net/docs/resources/20-colors/
*/
const distinctiveColors = {
red: [230, 25, 75],
green: [60, 180, 75],
yellow: [255, 255, 25],
blue: [67, 99, 216],
orange: [245, 130, 49],
purple: [145, 30, 180],
cyan: [66, 212, 244],
magenta: [240, 50, 230],
lime: [191, 239, 69],
pink: [250, 190, 212],
teal: [70, 153, 144],
lavender: [220, 190, 255],
brown: [154, 99, 36],
beige: [255, 250, 200],
maroon: [128, 0, 0],
mint: [170, 255, 195],
olive: [128, 128, 0],
apricot: [255, 216, 177],
navy: [0, 0, 117],
grey: [169, 169, 169],
white: [255, 255, 255],
black: [0, 0, 0],
};
/**
* Get a color for the given index.
*
* @param {number} index - The index of the color to get.
*/
function getColor(index) {
const distinctiveColorNames = Object.keys(distinctiveColors);
return distinctiveColorNames[index % distinctiveColorNames.length];
}
const usageDescription = `Convert Maya .obj and .mtl files into our JSON model format.
The polygons in the model are divided into chunks according to the material (i.e. the color) of \
each polygon. The output JSON model includes a list of vertex positions, and a list of chunks of \
polygons.`;
const contiguousOptionDescription = `Set whether the chunks in the output JSON model file should \
be contiguous. If unset, the pieces in each chunk might not be connected. If set, the chunks are \
fully connected, but there will be more chunks overall.`;
async function main() {
const { argv } = yargs(hideBin(process.argv))
.usage('$0 [options]', usageDescription, (_yargs) =>
_yargs
.option('out', {
default: 'fox.json',
description: 'The output file path',
type: 'string',
normalize: true,
})
.option('obj', {
default: 'fox.obj',
description: 'The input OBJ file path',
type: 'string',
normalize: true,
})
.option('mtl', {
default: 'fox.mtl',
description: 'The input MTL file path',
type: 'string',
normalize: true,
})
.option('gradient', {
description:
'The file path for an SVG file to take gradient definitions from',
type: 'string',
normalize: true,
})
.option('contiguous', {
default: false,
description: contiguousOptionDescription,
type: 'boolean',
})
.option('repaint', {
default: false,
description:
'Color and label each chunk with a distinctive color. This can makes chunks easier to identify.',
type: 'boolean',
}),
)
.version(false)
.strict();
const {
contiguous,
gradient,
out: outputFilename,
obj: objFilename,
mtl: mtlFilename,
repaint,
} = argv;
const [objContents, mtlContents, gradientSvgContents] = await Promise.all([
fs.readFile(objFilename, 'utf8'),
fs.readFile(mtlFilename, 'utf8'),
gradient ? fs.readFile(gradient, 'utf8') : null,
]);
const mtl = parseMTL(mtlContents);
const objFile = new OBJFile(objContents);
const data = objFile.parse(objFile);
/**
* A single position in 3D space. A position is represented by a tuple of X, Y, and Z
* coordinates.
*
* @typedef {[number, number, number]} Position
*/
/**
* An RGB color. The color is represented by a tuple of 3 numbers, which are the red, blue, and
* green values. Each value is an integer between 0 and 255.
*
* @typedef {[number, number, number]} RgbColor
*/
/**
* One face of the model. Each face is a triangle, and is represented by three vertices. Each
* vertex is present in the model's `position` array, and is represented as an index of this
* array.
*
* @typedef {[number, number, number]} Face
*/
/**
* A set of faces with the same color.
*
* @typedef {object} Chunk
* @property {RgbColor} color - The color of the chunk.
* @property {Array<Face>} faces - The faces included in this chunk.
*/
/**
* A JSON representation of a 3D model.
*
* @typedef Model
* @property {Array<Position>} positions - The vertex positions of the model.
* @property {Array<Chunk>} chunks - Sets of faces that share a common color.
* @property {Array<object>} [gradients] - Gradient definitions (see the types defined in `util.js`
* for details)
*/
/**
* @type {Partial<Model>}
*/
const output = {
positions: [],
};
const VI = 'vertexIndex';
const model = data.models[0];
model.vertices.forEach((v) => {
output.positions.push([v.x, v.y, v.z]);
});
const allChunks = [];
for (const mtlKey of Object.keys(mtl)) {
const m = mtl[mtlKey];
if (!m.Ka) {
throw new Error(`Invalid MTL entry at key '${mtlKey}'`);
}
const color = m.Kd.map(function (c) {
return Math.floor(255 * c);
});
m.Kd.forEach((c, i) => {
if (color[i] === 0) {
color[i] = Math.floor(255 * c);
}
});
let currentChunks = [];
model.faces.forEach((f, index) => {
// Skip faces that don't match the current color
if (f.material !== mtlKey) {
return;
}
const xVertex = f.vertices[0][VI] - 1;
const yVertex = f.vertices[1][VI] - 1;
const zVertex = f.vertices[2][VI] - 1;
// A polygon represents a single face, including its index in the underlying model and its
// vertices. This representation is used so that we can preserve the polygon order within
// each chunk.
const polygon = { index, vertices: [xVertex, yVertex, zVertex] };
// Non-contiguous chunks contain all polygons of a given color
if (!contiguous) {
if (currentChunks.length) {
currentChunks[0].polygons.push(polygon);
} else {
currentChunks.push({ color, polygons: [polygon] });
}
return;
}
// Search the current list of chunks for the current color that include an adjacent polygon.
// A polygon is adjacent if it shares two vertices.
const chunksWithAdjacentPolygons = currentChunks.filter((chunk) =>
chunk.polygons.some(
({ vertices }) =>
(vertices.includes(xVertex) &&
(vertices.includes(yVertex) || vertices.includes(zVertex))) ||
(vertices.includes(yVertex) && vertices.includes(zVertex)),
),
);
let chunk;
if (chunksWithAdjacentPolygons.length === 0) {
// If no chunks with adjacent polygons are found, this polygon forms a new chunk
chunk = { color, polygons: [] };
currentChunks.push(chunk);
} else if (chunksWithAdjacentPolygons.length === 1) {
// If a single chunk with an adjacent polygon is found, this polygon joins that chunk.
chunk = chunksWithAdjacentPolygons[0];
} else {
// If multiple chunks with an adjacent polygon are found, they are merged together before
// adding the new polygon.
chunk = chunksWithAdjacentPolygons[0];
const chunksToMerge = chunksWithAdjacentPolygons.slice(1);
for (const chunkToMerge of chunksToMerge) {
chunk.polygons.push(...chunkToMerge.polygons);
}
currentChunks = currentChunks.filter(
(_chunk) => !chunksToMerge.includes(_chunk),
);
// I don't know if order really matters here, but, it has been preserved just in case
chunk.polygons.sort((faceA, faceB) => faceA.index - faceB.index);
}
chunk.polygons.push(polygon);
});
allChunks.push(...currentChunks);
}
output.chunks = allChunks.map((chunk, index) => {
const finalChunk = {
color: chunk.color,
// The final model includes just the vertices of each face. The index is not needed.
faces: chunk.polygons.map(({ vertices }) => vertices),
};
if (repaint) {
const colorName = getColor(index);
finalChunk.name = colorName;
finalChunk.color = distinctiveColors[colorName];
}
return finalChunk;
});
if (gradientSvgContents) {
const svgRoot = parse(gradientSvgContents);
assert.equal(svgRoot.children.length, 1);
const svgElement = svgRoot.children[0];
const { width, height } = svgElement.properties || {};
assert.equal(typeof width, 'number');
assert.equal(typeof height, 'number');
const defsElements = svgElement.children.filter(
(child) => child.tagName === 'defs',
);
assert.equal(defsElements.length, 1);
const defsElement = defsElements[0];
// Add padding to reflect that the 3D model has more padding than the SVG
// These are percentages
const leftPadding = 10;
const rightPadding = 10;
const topPadding = 10;
const bottomPadding = 10;
const xScalingRatio = (100 - leftPadding - rightPadding) / 100;
const yScalingRatio = (100 - topPadding - bottomPadding) / 100;
const xTranslation = leftPadding;
const yTranslation = topPadding;
const gradients = {};
for (const child of defsElement.children) {
if (child.tagName === 'linearGradient') {
const linearGradient = { type: 'linear', stops: [] };
let id;
for (const propertyName of Object.keys(child.properties || {})) {
const value = child.properties[propertyName];
if (propertyName === 'id') {
id = value;
} else if (['x1', 'x2'].includes(propertyName)) {
assert.equal(typeof value, 'number');
const percentage =
(value / width) * 100 * xScalingRatio + xTranslation;
assert.ok(Number.isFinite(percentage));
linearGradient[propertyName] = `${percentage}%`;
} else if (['y1', 'y2'].includes(propertyName)) {
assert.equal(typeof value, 'number');
const percentage =
(value / height) * 100 * yScalingRatio + yTranslation;
assert.ok(Number.isFinite(percentage));
linearGradient[propertyName] = `${percentage}%`;
} else {
linearGradient[propertyName] = value;
}
}
assert.ok(id);
const stopNodes = child.children.filter(
(potentialStopNode) => potentialStopNode.tagName === 'stop',
);
for (const stopNode of stopNodes) {
linearGradient.stops.push(stopNode.properties);
}
gradients[id] = linearGradient;
} else if (child.tagName === 'radialGradient') {
const radialGradient = { type: 'radial', stops: [] };
let id;
for (const propertyName of Object.keys(child.properties || {})) {
const value = child.properties[propertyName];
if (propertyName === 'id') {
id = value;
} else if (['cx', 'fr', 'fx', 'r'].includes(propertyName)) {
assert.equal(typeof value, 'number');
const percentage =
(value / width) * 100 * xScalingRatio + xTranslation;
assert.ok(Number.isFinite(percentage));
radialGradient[propertyName] = `${percentage}%`;
} else if (['cy', 'fy'].includes(propertyName)) {
assert.equal(typeof value, 'number');
const percentage =
(value / height) * 100 * yScalingRatio + yTranslation;
assert.ok(Number.isFinite(percentage));
radialGradient[propertyName] = `${percentage}%`;
} else {
radialGradient[propertyName] = value;
}
}
assert.ok(id);
const stopNodes = child.children.filter(
(potentialStopNode) => potentialStopNode.tagName === 'stop',
);
for (const stopNode of stopNodes) {
radialGradient.stops.push(stopNode.properties);
}
gradients[id] = radialGradient;
}
}
if (Object.keys(gradients).length > 0) {
output.gradients = gradients;
} else {
console.warn('No gradients found');
}
}
const stringifiedOutput = JSON.stringify(output, null, 2);
const formattedOutput = prettier.format(stringifiedOutput, {
filepath: outputFilename,
});
await fs.writeFile(outputFilename, formattedOutput);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});