Skip to content
On this page

Loading glTF with KHR_materials_pbrSpecularGlossiness in three.js

Newer versions of three.js do not include spec/gloss PBR materials. The model must be converted to metal/rough PBR materials.

More - https://stackoverflow.com/a/75889212/2229899

Runtime in three.js

When loading in three.js GLTFLoader, the plugin/extension can be used to automatically convert the binary data to metal/rough PBR materials.

typescript
const gltfKhrPbrSpecularGlossinessConverter = (confirm?: (s: string)=>Promise<boolean>)=>(parser: GLTFParser)=>({
    name: 'KHR_materials_pbrSpecularGlossiness',
    beforeRoot: async() => {
        if (confirm && !await confirm('Convert KHR_materials_pbrSpecularGlossiness to KHR_materials_pbrMetallicRoughness?')) return

        const json = parser.json
        const io = new WebIO().registerExtensions(ALL_EXTENSIONS)/*.registerExtensions(ALL_WEBGI_EXTENSIONS)*/
        const document = await io.readJSON({json, resources: {
            ['@glb.bin']: new Uint8Array(parser.extensions.KHR_binary_glTF?.body),
        }})

        // Convert materials.
        await document.transform(metalRough())

        // Write back to GLB.
        const res = await io.writeBinary(document)
        const binaryExtension = new GLTFBinaryExtension(res.buffer as any)
        parser.extensions.KHR_binary_glTF = binaryExtension
        parser.json = JSON.parse(binaryExtension.content)
    },
})

// Sample usage
const loader = new GLTFLoader();
loader.register(gltfKhrPbrSpecularGlossinessConverter());

loader.load('file.glb');

In webgi, threepipe, this extension is available with GLTFSpecGlossinessConverterPlugin, simply add it to the viewer, and any model with KHR_materials_pbrSpecularGlossiness will be converted to KHR_materials_pbrMetallicRoughness while load.

javascript
viewer.addPluginSync(GLTFSpecGlossinessConverterPlugin)

UI conversion

Load the model into https://gltf.report/, accept the prompt to convert the material, and then export the result to a new file.

Offline command-line conversion

bash
npm install --global @gltf-transform/cli

gltf-transform metalrough input.glb output.glb

Made with ❤️ using the awesome vitepress