75 lines
1.9 KiB
TypeScript
75 lines
1.9 KiB
TypeScript
import { ModelStore, MsonEvaluatedModel } from '../mson';
|
|
import { promises as fs } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { Object3D } from 'three';
|
|
|
|
export const fillStoreFromFilesystem = async (
|
|
store: ModelStore,
|
|
root: string,
|
|
) => {
|
|
// Get all mod prefixes from the input directory.
|
|
const prefixes = (await fs.readdir(root, { withFileTypes: true }))
|
|
.filter((item) => item.isDirectory())
|
|
.map((item) => item.name);
|
|
|
|
// Loop through all of the prefixes
|
|
for (const prefix of prefixes) {
|
|
// Prefix absolute path
|
|
const prefixPath = join(root, prefix);
|
|
|
|
// Recurse all of the files in the mod directory
|
|
const allFiles = await fs.readdir(prefixPath, {
|
|
recursive: true,
|
|
withFileTypes: true,
|
|
});
|
|
|
|
// Loop through all JSON files
|
|
for (const dirent of allFiles) {
|
|
if (!dirent.isFile()) continue;
|
|
if (!dirent.name.endsWith('.json')) continue;
|
|
const absPath = join(dirent.path, dirent.name);
|
|
|
|
// Relative path of model
|
|
const relPath = absPath.replace(prefixPath, '');
|
|
|
|
// Model file contents
|
|
const readFile = await fs.readFile(absPath, { encoding: 'utf-8' });
|
|
const parsed = JSON.parse(readFile);
|
|
|
|
// Component name referenced from other models
|
|
const componentName = `${prefix}:${relPath.replace('.json', '').substring(1)}`;
|
|
|
|
// Insert component into the store
|
|
store.insertModel(componentName, parsed);
|
|
}
|
|
}
|
|
};
|
|
|
|
export const saveGeometry = async (
|
|
root: string,
|
|
name: string,
|
|
object: Object3D,
|
|
) =>
|
|
await fs.writeFile(
|
|
join(root, `${name}.json`),
|
|
JSON.stringify(object.toJSON()),
|
|
);
|
|
|
|
export const saveModel = async (
|
|
root: string,
|
|
name: string,
|
|
data: MsonEvaluatedModel,
|
|
) =>
|
|
await fs.writeFile(
|
|
join(root, `${name}.mson.json`),
|
|
JSON.stringify(
|
|
{
|
|
texture: data.texture,
|
|
locals: data._localsEvaluated,
|
|
data: data._dataEvaluated,
|
|
},
|
|
undefined,
|
|
2,
|
|
),
|
|
);
|