Load GLTF file that is not located in Public folder

Viewed 265

I found a problem that I cannot load GLTF files into a scene if I cannot place them in the Public folder in my React application. For example, I have MyPVPanel.gltf, and I want to load it in react app or in my npm library, or I always to be with my react components. enter image description here

My questions are:

  • Is this possible to import assets from a specific folder if you develop an npm package. Do packages have something like /public or /assets?
  • Can I configure my own package to have such a folder with static assets?
  • How to load GLTF files without a public folder. For example, we can import .png files without problems in react application.
1 Answers

So there is a thing named data URI. You can convert small files in that format(which is basically a base64 encoded string with some metadata at the beginning of it).

data:[<mediatype>][;base64],<data>

In my case [<mediatype>] is data:application/octet-stream.

So if you want to load small file from specific folder in you application, first of all rename your .gltf file into .json. And after importing and converting it into base64 code you can load it using GLTFLoader from three.js library.
Here is a code example:

import myGLTF from './MyPVPanel.json';
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader";
import myGLTF from "./MyPVPanel.json";

const loader = new GLTFLoader();

const stringGLTF = JSON.stringify(myGLTF) // convert Object to a String
const base64EncodedGLTF = btoa(stringGLTF) // Base64 encode the String

//First part is: 'data:application/octet-stream;base64,'
const resultingDataURI = `data:application/octet-stream;base64,${base64EncodedGLTF}`;

loader.load(
  resultingDataURI,
  (gltf: any) => {
    console.log('Loaded!!!');
    this.scene.add(gltf.scene)
  },
  () => {},
  (e: any) => console.error(e)
);
}}>Load</button>
Related