GLSL:如果未绑定任何Uniform,则强制错误



我将GLSL 1.0与WebGL 1.0和2.0一起使用,我只是花了几个小时来解决一个问题,在我看来,这个问题应该在开始之前就引发错误。

我的片段着色器中有uniformssampler2D。我更改了一行代码,该更改导致没有输入纹理或数组绑定到Shaderuniforms的位置。然而,该程序运行时没有问题,但在读取这些uniforms时会产生零。例如,对texture2D(MyTexture, vec2(x,y))的调用不会抛出任何错误,而只是返回0。

在渲染之前或渲染过程中,我是否可以强制将其作为错误?

更新:有一个库可以执行下面提到的一些检查:请参阅webgl-int-


没有办法让WebGL自己检查您的错误。如果您想检查错误,可以编写自己的包装器。例如,有一个webgl调试上下文包装器,它在每个webgl命令之后调用gl.getError

遵循类似的模式,您可以尝试检查是否未设置统一,方法是包装与绘图、程序、统一、属性等相关的所有函数,或者只制作称为的函数

function myUseProgram(..args..) {
checkUseProgramStuff();
gl.useProgram(..);
}
function myDrawArrays(..args..) {
checkDrawArraysStuff();
gl.drawArrays(..args..);
}

对于制服,您需要跟踪程序成功链接的时间,然后在其所有制服上循环(您可以查询(。跟踪当前程序是什么。跟踪对gl.uniform的调用以跟踪是否设置了制服。

这里有一个的例子

(function() {
const gl = null;  // just to make sure we don't see global gl
const progDB = new Map();
let currentUniformMap;
const limits = {};
const origGetUniformLocationFn = WebGLRenderingContext.prototype.getUniformLocation;
function init(gl) {
[gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS].forEach((pname) => {
limits[pname] = gl.getParameter(pname);
});
}
function isBuiltIn(info) {
const name = info.name;
return name.startsWith("gl_") || name.startsWith("webgl_");
}
function addProgramToDB(gl, prg) {
const uniformMap = new Map();
const numUniforms = gl.getProgramParameter(prg, gl.ACTIVE_UNIFORMS);
for (let ii = 0; ii < numUniforms; ++ii) {
const uniformInfo = gl.getActiveUniform(prg, ii);
if (isBuiltIn(uniformInfo)) {
continue;
}
const location = origGetUniformLocationFn.call(gl, prg, uniformInfo.name);
uniformMap.set(location, {set: false, name: uniformInfo.name, type: uniformInfo.type, size: uniformInfo.size});
}
progDB.set(prg, uniformMap);
}
HTMLCanvasElement.prototype.getContext = function(origFn) {
return function(type, ...args) {
const ctx = origFn.call(this, type, ...args);
if (ctx && type === 'webgl') {
init(ctx);
}
return ctx;
}
}(HTMLCanvasElement.prototype.getContext);
// getUniformLocation does not return the same location object
// for the same location so mapping a location to uniform data
// would be a PITA. So, let's make it return the same location objects.
WebGLRenderingContext.prototype.getUniformLocation = function(origFn) {
return function(prg, name) {
const uniformMap = progDB.get(prg);
for (const [location, uniformInfo] of uniformMap.entries()) {
// note: not handling names like foo[0] vs foo
if (uniformInfo.name === name) {
return location;
}
}
return null;
};
}(WebGLRenderingContext.prototype.getUniformLocation);
WebGLRenderingContext.prototype.linkProgram = function(origFn) {
return function(prg) {
origFn.call(this, prg);
const success = this.getProgramParameter(prg, this.LINK_STATUS);
if (success) {
addProgramToDB(this, prg);
}
};
}(WebGLRenderingContext.prototype.linkProgram);
WebGLRenderingContext.prototype.useProgram = function(origFn) {
return function(prg) {
origFn.call(this, prg);
currentUniformMap = progDB.get(prg);
};
}(WebGLRenderingContext.prototype.useProgram);
WebGLRenderingContext.prototype.uniform1i = function(origFn) {
return function(location, v) {
const uniformInfo = currentUniformMap.get(location);
if (v === undefined) {
throw new Error(`bad value for uniform: ${uniformInfo.name}`);  // do you care? undefined will get converted to 0
}
const val = parseFloat(v);
if (isNaN(val) || !isFinite(val)) {
throw new Error(`bad value NaN or Infinity for uniform: ${uniformInfo.name}`);  // do you care?
}
switch (uniformInfo.type) {
case this.SAMPLER_2D:
case this.SAMPLER_CUBE:
if (val < 0 || val > limits[this.MAX_COMBINED_TEXTURE_IMAGE_UNITS]) {
throw new Error(`texture unit out of range for uniform: ${uniformInfo.name}`);
}
break;
default:
break;
}
uniformInfo.set = true;
origFn.call(this, location, v);
};
}(WebGLRenderingContext.prototype.uniform1i);
WebGLRenderingContext.prototype.drawArrays = function(origFn) {
return function(...args) {
const unsetUniforms = [...currentUniformMap.values()].filter(u => !u.set);
if (unsetUniforms.length) {
throw new Error(`unset uniforms: ${unsetUniforms.map(u => u.name).join(', ')}`);
}
origFn.call(this, ...args);
};
}(WebGLRenderingContext.prototype.drawArrays);
}());
// ------------------- above is wrapper ------------------------
// ------------------- below is test ---------------------------
const gl = document.createElement('canvas').getContext('webgl');
const vs = `
uniform float foo;
uniform float bar;
void main() {
gl_PointSize = 1.;
gl_Position = vec4(foo, bar, 0, 1);
}
`;
const fs = `
precision mediump float;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, vec2(0));
}
`;
const prg = twgl.createProgram(gl, [vs, fs]);
const fooLoc = gl.getUniformLocation(prg, 'foo');
const barLoc = gl.getUniformLocation(prg, 'bar');
const texLoc = gl.getUniformLocation(prg, 'tex');
gl.useProgram(prg);
test('fails with undefined', () => {
gl.uniform1i(fooLoc, undefined);
});
test('fails with non number string', () => {
gl.uniform1i(barLoc, 'abc');
});
test('fails with NaN', () => {
gl.uniform1i(barLoc, 1/0);
});
test('fails with too large texture unit', () => {
gl.uniform1i(texLoc, 1000);
})
test('fails with not all uniforms set', () => {
gl.drawArrays(gl.POINTS, 0, 1);
});
test('fails with not all uniforms set',() => {
gl.uniform1i(fooLoc, 0);
gl.uniform1i(barLoc, 0);
gl.drawArrays(gl.POINTS, 0, 1);
});
test('passes with all uniforms set', () => {
gl.uniform1i(fooLoc, 0);
gl.uniform1i(barLoc, 0);
gl.uniform1i(texLoc, 0);
gl.drawArrays(gl.POINTS, 0, 1);   // note there is no texture so will actually generate warning
});
function test(msg, fn) {
const expectFail = msg.startsWith('fails');
let result = 'success';
let fail = false;
try {
fn();
} catch (e) {
result = e;
fail = true;
}
log('black', msg);
log(expectFail === fail ? 'green' : 'red', '  ', result);
}
function log(color, ...args) {
const elem = document.createElement('pre');
elem.textContent = [...args].join(' ');
elem.style.color = color;
document.body.appendChild(elem);
}
pre { margin: 0; }
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>

上面的代码仅包装gl.uniform1i。它不处理统一数组,也不处理单个数组元素的位置。它确实展示了一种追踪制服的方法,以及制服是否已经定型。

按照类似的模式,你可以检查每个纹理单元是否分配了纹理等,每个属性是否打开等

当然,你也可以编写自己的WebGL框架来跟踪所有这些东西,而不是破解WebGL上下文本身。换句话说,例如three.js可以跟踪它的所有统一设置在比WebGL级别更高的级别,并且您自己的代码可以做类似的事情。

至于为什么WebGL不发出错误,有很多原因。首先,不设置制服不是错误。统一格式有默认值,使用默认值完全可以。

浏览器确实遇到了一些问题,但由于WebGL是流水线式的,它无法在发出命令时给你错误,而不会大大降低性能(上面提到的调试上下文会帮你做到这一点(。因此,浏览器有时可以在控制台中发出警告,但它无法在您发出命令时停止您的JavaScript。无论如何,它可能没有那么大帮助,因为它唯一经常出错的地方是在绘图时。换句话说,之前发出的30-100个设置WebGL状态的命令在绘制之前不会出错,因为您可以在绘制之前的任何时候修复该状态。因此,您在draw中得到了错误,但这并不能告诉您之前30-100个命令中的哪一个导致了问题。

最后还有一个哲学问题,即尝试通过emscripten或WebAssembly支持OpenGL/ENGGLES的本地端口。许多本机应用程序忽略许多GL错误,但仍在运行。这就是WebGL不抛出的原因之一,以保持与OpenGL ES的兼容性(以及上述原因(。这也是为什么大多数WebGL实现只显示一些错误,然后打印"错误"的原因;将不再显示webgl错误";因为浏览器不希望忽略WebGL错误的程序用日志消息填充内存。

幸运的是,如果你真的想要它,你可以自己写支票。

最新更新