Search code examples
node.jsmergetransformgltf

Use GLTF-transform merge command - node js script


I want to use the gltf-transform command "merge" in my script and wrote something like this to merge two or more gltf files.

const { merge } = require('@gltf-transform/cli');
const fileA = '/model_path/fileA.gltf';
const fileB = '/model_path/fileB.gltf';

merge(fileA, fileB, output.gltf, false);

But nothing happened. No output file or console log. So I dont know where to continue my little journey.

Would be great when someone has a clue.

An alternative was...

const command = "gltf-transform merge("+fileA+", "+fileB+", output.gltf, false)";
exec(command, (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

... but didnt work either and looks needless.


Solution

  • The @gltf-transform/cli package you're importing isn't really designed for programmatic usage; it's just a CLI. Code meant for programmatic use is in the /functions, /core, and /extensions packages.

    If you'd like to implement something similar in JavaScript, I would try this instead:

    import { Document, NodeIO } from '@gltf-transform/core';
    
    const io = new NodeIO();
    const inputDocument1 = io.read('./model_path/fileA.gltf');
    const inputDocument2 = io.read('./model_path/fileB.gltf');
    const outputDocument = new Document()
      .merge(inputDocument1)
      .merge(inputDocument2);
    
    // Optional: Merge binary resources to a single buffer.
    const buffer = doc.getRoot().listBuffers()[0];
    doc.getRoot().listAccessors().forEach((a) => a.setBuffer(buffer));
    doc.getRoot().listBuffers().forEach((b, index) => index > 0 ? b.dispose() : null);
    
    io.write('./model_path/output.gltf', outputDocument);
    

    This will create a single glTF file containing two scenes. If you wanted to merge the contents of both files into a single scene that would require moving some nodes around with the Scene API.