Skip to content

Instantly share code, notes, and snippets.

@Sgeo
Last active October 2, 2019 04:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sgeo/94130bee66d3895e61282df5adde1917 to your computer and use it in GitHub Desktop.
Save Sgeo/94130bee66d3895e61282df5adde1917 to your computer and use it in GitHub Desktop.
// This code is NOT spec compliant: An RGB texture can be mistaken for an intensity texture if all its pixels happen to be gray.
// I suspect this will not particularly affect a lot of textures, but it is a possibility
// This also needs to check all URLs rather than the first, preferably the same way X3DOM does if possible
// Also better error handling
function fixGray(imageTexture) {
var url = imageTexture.getFieldValue("url")[0];
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var imageData = ctx.getImageData(0, 0, this.width, this.height);
var gray = true;
for(let i = 0; i < imageData.data.length; i+=4) {
if(imageData.data[i] != imageData.data[i+1] || imageData.data[i+1] != imageData.data[i+2]) {
gray = false;
break;
}
}
console.log("ImageTexture url = ", url, "gray = ", gray);
if(gray) {
imageTexture.setFieldValue("origChannelCount", 1);
}
};
img.src = url;
}
x3dom.runtime.ready = function() {
let imagetextures = document.querySelectorAll("ImageTexture");
globalThis.imagetextures = imagetextures;
for (imageTexture of imagetextures) {
console.log("imageTexture = ", imageTexture);
try {
fixGray(imageTexture);
} catch(e) {
console.error("No origChannelCount?");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment