Skip to content

Refactor useGLTF #609

@alvarosabu

Description

@alvarosabu

Description

Based on breaking changes from the core Tresjs/tres#959. Refactor useGLTF to use https://vueuse.org/core/useAsyncState/#useasyncstate

Suggested solution

export function useGLTF(path: MaybeRef<string>, options?: {
  draco?: boolean
  manager?: LoadingManager
  asyncOptions?: UseAsyncStateOptions<true, any | null>
}) {
  const loader = new GLTFLoader(options?.manager)
  if (options?.draco) {
    const dracoLoader = new DRACOLoader()
    dracoLoader.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.6/')
    loader.setDRACOLoader(dracoLoader)
  }

  const initialPath = toValue(path)

  const result = useAsyncState(
    (path?: string) => new Promise((resolve, reject) => {
      loader.load(path || initialPath || '', (result: GLTF) => {
        const loadedData = result
        if (loadedData.scene) {
          const graph = buildGraph(loadedData.scene)
          Object.assign(loadedData, graph.value)
        }
        resolve(loadedData as unknown as TresObject)
      }, undefined, (err: unknown) => {
        reject(err)
      })
    }),
    null,
    {
      ...options?.asyncOptions,
      immediate: options?.asyncOptions?.immediate ?? true,
    },
  )

  return result as UseAsyncStateReturn<GLTF & TresObjectMap, [string], true>
}
~``

### Alternative

_No response_

### Additional context

_No response_

### Validations

- [x] I agree to follow this project's [Code of Conduct](https://github.com/Tresjs/cientos/blob/main/CODE_OF_CONDUCT.md)
- [x] Read the [Contributing Guidelines](https://github.com/Tresjs/cientos/blob/main/CONTRIBUTING.md).
- [x] Read the [docs](https://cientos.tresjs.org/guide).
- [x] Check that there isn't [already an issue](https://github.com/tresjs/cientos/issues) that reports the same bug to avoid creating a duplicate.

Metadata

Metadata

Assignees

Projects

Status

No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions