How to change .gltf buffer uri in react?

608 views Asked by At

Information of the .gltf file that already exists. Information of the .gltf file that already exists. . . .

"buffers" : [
            {
                "byteLength" : 472360,
                "uri" : "non-existent-file.bin"
            }
        ]

This is my code that I want to change the Buffer URI of this file after loading it first.

> var loader = new GLTFLoader();
> 
>   loader.load(
>     exist_gltf_file_path,
>     (gltf) => {
>       gltf.buffers[0].uri = gltf.buffers[0].uri.replace("non-existent file.bin", "new_file.bin");
>     },
>     (xhr) => {
>       console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
>     },
>     (error) => {
>       console.log("An error happened");
>     }   );

Here an error occurs in load because the uri path of the buffer does not exist. I'd like to change my URI before LOAD, what should I do?

2

There are 2 answers

4
hgb123 On

You could replace with regex

const data = {
  buffers: [
    {
      byteLength: 472360,
      uri: "494E996610D342DF.bin",
    },
  ],
}

data.buffers[0].uri = data.buffers[0].uri.replace(/.*(.bin)/, "yournewname$1")

console.log(data)

2
emackey On

The problem is you won't be able to successfully call GLTFLoader .load() function with an invalid glTF buffer as part of the file.

The .load function does two things: (1) It fetches (async) and parses the JSON from the server, and then (2) it parses the resulting object as glTF. The problem is you're trying to edit the thing between steps (1) and (2), but this .load function is doing both.

I don't know about the reactjs version, but if this is based on ThreeJS, the GLTFLoader class has another helper function called .parse(...) that takes different arguments and only does step (2) mentioned above. Note that this is NOT a JSON.parse (which happened in step 1), this is parsing the resulting JSON object tree into a full glTF 3D model. So you would then need to take care of step (1) yourself, possibly doing it the way GLTFLoader does it.

But this gives you the chance to make edits to the loaded/parsed JSON before asking GLTFLoader to then parse the resulting object into a 3D model.