Mike0021 commited on
Commit
6ce4f2d
·
verified ·
1 Parent(s): 5a48780

Add export_glb.mjs

Browse files
Files changed (1) hide show
  1. export_glb.mjs +63 -0
export_glb.mjs ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Turn a LowPoly Coder 4B reply into a .glb file.
2
+ //
3
+ // npm install three@0.180.0
4
+ // node export_glb.mjs reply.txt asset.glb
5
+ //
6
+ // reply.txt is the model's full answer (spec lines + one ```javascript block defining buildAsset(THREE)).
7
+ // The code runs in a node:vm context with a time limit. node:vm is NOT a security boundary: generated code
8
+ // is untrusted, so run this inside a container or VM without network or secrets.
9
+ //
10
+ // Output: one glTF node per mesh (named as in the code), world transforms baked into the vertices,
11
+ // one material per mesh (base colour from MeshStandardMaterial.color, metallic/roughness copied).
12
+ // Triangles are written unindexed and without normals, so glTF viewers shade them flat, as intended.
13
+ import fs from 'node:fs';
14
+ import vm from 'node:vm';
15
+ import * as THREE from 'three';
16
+
17
+ const [, , inPath, outPath = 'asset.glb'] = process.argv;
18
+ if (!inPath) { console.error('usage: node export_glb.mjs reply.txt [asset.glb]'); process.exit(2); }
19
+ const reply = fs.readFileSync(inPath, 'utf8').split('</think>').pop();
20
+ const blocks = [...reply.matchAll(/```(?:javascript|js)?\s*\n([\s\S]*?)```/g)].map(m => m[1]);
21
+ const code = blocks.find(b => b.includes('function buildAsset'));
22
+ if (!code) { console.error('no ```javascript block with function buildAsset found'); process.exit(1); }
23
+
24
+ const ctx = vm.createContext({ THREE, Math, console });
25
+ const root = new vm.Script(code + '\n;buildAsset(THREE);').runInContext(ctx, { timeout: 10000 });
26
+ if (!root || !root.isObject3D) { console.error('buildAsset did not return a THREE.Object3D'); process.exit(1); }
27
+ root.updateMatrixWorld(true);
28
+
29
+ const meshes = [];
30
+ root.traverse(o => { if (o.isMesh && o.geometry?.attributes?.position) meshes.push(o); });
31
+ if (!meshes.length) { console.error('no meshes'); process.exit(1); }
32
+
33
+ const chunks = [], json = { asset: { version: '2.0', generator: 'lowpoly-coder-4b export_glb.mjs' }, scene: 0,
34
+ scenes: [{ name: root.name || 'asset', nodes: [] }], nodes: [], meshes: [], materials: [], accessors: [], bufferViews: [], buffers: [] };
35
+ let offset = 0, triangles = 0;
36
+ for (const m of meshes) {
37
+ const g = m.geometry.index ? m.geometry.toNonIndexed() : m.geometry;
38
+ const p = g.attributes.position, v = new THREE.Vector3();
39
+ const pos = new Float32Array(p.count * 3), mn = [Infinity, Infinity, Infinity], mx = [-Infinity, -Infinity, -Infinity];
40
+ for (let i = 0; i < p.count; i++) {
41
+ v.fromBufferAttribute(p, i).applyMatrix4(m.matrixWorld);
42
+ const a = [v.x, v.y, v.z];
43
+ for (let k = 0; k < 3; k++) { pos[i * 3 + k] = a[k]; mn[k] = Math.min(mn[k], a[k]); mx[k] = Math.max(mx[k], a[k]); }
44
+ }
45
+ if (!pos.every(Number.isFinite)) { console.error(`mesh "${m.name}" has non-finite coordinates`); process.exit(1); }
46
+ const mat = Array.isArray(m.material) ? m.material[0] : m.material, c = mat?.color ?? new THREE.Color(0.8, 0.8, 0.8);
47
+ json.materials.push({ name: mat?.name || m.name, pbrMetallicRoughness: { baseColorFactor: [c.r, c.g, c.b, 1],
48
+ metallicFactor: mat?.metalness ?? 0, roughnessFactor: mat?.roughness ?? 1 }, doubleSided: false });
49
+ json.bufferViews.push({ buffer: 0, byteOffset: offset, byteLength: pos.byteLength, target: 34962 });
50
+ json.accessors.push({ bufferView: json.bufferViews.length - 1, componentType: 5126, count: p.count, type: 'VEC3', min: mn, max: mx });
51
+ json.meshes.push({ name: m.name, primitives: [{ attributes: { POSITION: json.accessors.length - 1 }, material: json.materials.length - 1 }] });
52
+ json.nodes.push({ name: m.name || `mesh_${json.nodes.length}`, mesh: json.meshes.length - 1 });
53
+ json.scenes[0].nodes.push(json.nodes.length - 1);
54
+ chunks.push(Buffer.from(pos.buffer)); offset += pos.byteLength; triangles += p.count / 3;
55
+ }
56
+ json.buffers.push({ byteLength: offset });
57
+ const pad = (b, fill) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4, fill)]);
58
+ const jsonBuf = pad(Buffer.from(JSON.stringify(json)), 0x20), binBuf = pad(Buffer.concat(chunks), 0);
59
+ const header = Buffer.alloc(12), jh = Buffer.alloc(8), bh = Buffer.alloc(8);
60
+ header.writeUInt32LE(0x46546c67, 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + binBuf.length, 8);
61
+ jh.writeUInt32LE(jsonBuf.length, 0); jh.writeUInt32LE(0x4e4f534a, 4); bh.writeUInt32LE(binBuf.length, 0); bh.writeUInt32LE(0x004e4942, 4);
62
+ fs.writeFileSync(outPath, Buffer.concat([header, jh, jsonBuf, bh, binBuf]));
63
+ console.log(`wrote ${outPath}: ${meshes.length} meshes, ${triangles} triangles`);