Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useVariants hook to use KHR Material Variants #2115

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

DennisSmolek
Copy link
Contributor

image

Live Sandbox

Why

The KHR Material Variants GLTF Extension allows you to set multiple materials on multiple meshes within a single GLTF instance. This allows you to create many different versions of objects inside a single gltf file and set a global state object to switch between them.

This is supported within threeJS core: Here

What

This hook takes the returned GLTF object from the standard loader or loaders like useGLTF

const gltf = useGLTF('model.glb');
const { activeVariant, setVariant, variants, materials } = useVariants(gltf);

activeVariant is the string name of the current variant
setVariant takes the string name input of the variant object
variants is an array of of variants that look like { name: 'variantName' } ( NOTE: I was originally going to simplify this to just be the variant names, but talking with Don it would be possible to add data to variant objects that could be useful. Leaving it this way makes that data accessible)
materials This is less commonly used but is the actual materials array from the GLTF. apps like GLTFJSX actually struggle with gltf material lists and can accidentally merge them or mess them up. Because we are already deep into the GLTF I added this to help me pull them out and read them if needed. It will probably be ignored by most.

You can set the variant using the setVariant method or as an input to the hook itself.
This makes things convienent when the switching logic happens outside the component.

Using setVariant()

const gltf = useGLTF('model.glb')
const { setVariant } = useVariants(gltf)

useEffect(() => {
  setVariant(props.variant)
}, [props.variant])

Using direct hook input:

const gltf = useGLTF('model.glb')
useVariants(gltf, props.variant)

Checklist

  • [x ] Documentation updated (example)
  • [x ] Storybook entry added (example)
  • [x ] Ready to be merged

Copy link

vercel bot commented Oct 4, 2024

@DennisSmolek is attempting to deploy a commit to the Poimandres Team on Vercel.

A member of the Team first needs to authorize it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant