Skip to content

One loader to rule them all #30635

@mudroljub

Description

@mudroljub

Description

There are many different file types for 3d models and many different loaders in Three.js.

In my hobby project I solved it by creating an abstraction - the loadModel function receives any file and loads it, using the appropriate loader, without the user having to choose and import the appropriate loader himself.

Solution

This is the main function that calls the appropriate loader based on the file type:

export const loadModel = async param => {
  const params = typeof param === 'object' ? param : { file: param }
  const ext = params.file.split('.').pop()
  switch (ext) {
    case 'obj':
      return loadObj(params)
    case 'glb':
    case 'gltf':
      return loadGlb(params)
    case 'dae':
      return loadDae(params)
    case 'md2':
      return loadMd2(params)
    case 'fbx':
      const { prefix, file, animDict } = params
      if (prefix) {
        params.file = prefix + file
        if (animDict) params.animations = await loadFbxAnimations(animDict, prefix)
      }
      return loadFbx(params)
    default:
      throw new Error(`Unknown file extension: ${ext}`)
  }
}

You can see the rest of the logic here:
https://github.com/create-3d-worlds/create-3d-worlds.github.io/blob/master/core/loaders.js

Alternatives

P.s. I am not proposing to copy-paste my solution, but to implement a similar pattern.

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions