Metallic and roughness textures in PBR

I also posted about this in the past , it was not something babylon was interested to expose themselves so I resorted to adding this functionality at runtime myself , here is my function , but take note :

• It was specific to my usage and I didnt need to control metallic variations , so I just used the loaded roughness texture and white values for all other channels. If you want to control both you would need to read the current metallicTexture ( if it exists ) and write only the roughness to it. etc

• I stored/cached the texture I created onto the material to avoid running the code again if not needed , this could be a memory concern but again , it is a controlled environment and I know my usage of this will not cause issues for me.

That all said , the code should point you in the direction you need and you can makee any changes you require :

Object.defineProperty(PBRBaseMaterial.prototype, "roughnessTexture", {
    configurable: true,
    set: function (newValue) {
      if (this[newValue.name]) {
        this.metallicTexture = this[newValue.name];
        return;
      }
      let texBuff;
      newValue.readPixels().then((val) => {
        texBuff = val;
        for (let i = 0; i < texBuff.length; i += 4) {
          texBuff[i] = 255;
          texBuff[i + 2] = 255;
          texBuff[i + 3] = 255;
        }
        let dimention = Math.sqrt(texBuff.length / 4);
        this[newValue.name] = new RawTexture(texBuff, dimention, dimention, 5, scene, true, true);
        this.roughness = 1;
        this.useRoughnessFromMetallicTextureAlpha = false;
        this.useRoughnessFromMetallicTextureGreen = true;
        this.metallicTexture = this[newValue.name];
      });
    },
  });
3 Likes