@luma.gl/gltools
Version:
WebGL2 API Polyfills for WebGL1 WebGLRenderingContext
95 lines (85 loc) • 2.39 kB
JavaScript
import { polyfillVertexArrayObject } from './polyfill-vertex-array-object';
import { assert } from '../utils/assert';
import { WEBGL2_CONTEXT_POLYFILLS, WEBGL2_CONTEXT_OVERRIDES } from './polyfill-table';
export function polyfillContext(gl) {
gl.luma = gl.luma || {};
const {
luma
} = gl;
if (!luma.polyfilled) {
polyfillVertexArrayObject(gl);
initializeExtensions(gl);
installPolyfills(gl, WEBGL2_CONTEXT_POLYFILLS);
installOverrides(gl, {
target: luma,
target2: gl
});
luma.polyfilled = true;
}
return gl;
}
globalThis.polyfillContext = polyfillContext;
function initializeExtensions(gl) {
gl.luma.extensions = {};
const EXTENSIONS = gl.getSupportedExtensions() || [];
for (const extension of EXTENSIONS) {
gl.luma[extension] = gl.getExtension(extension);
}
}
function installOverrides(gl, _ref) {
let {
target,
target2
} = _ref;
Object.keys(WEBGL2_CONTEXT_OVERRIDES).forEach(key => {
if (typeof WEBGL2_CONTEXT_OVERRIDES[key] === 'function') {
const originalFunc = gl[key] ? gl[key].bind(gl) : () => {};
const polyfill = WEBGL2_CONTEXT_OVERRIDES[key].bind(null, gl, originalFunc);
target[key] = polyfill;
target2[key] = polyfill;
}
});
}
function installPolyfills(gl, polyfills) {
for (const extension of Object.getOwnPropertyNames(polyfills)) {
if (extension !== 'overrides') {
polyfillExtension(gl, {
extension,
target: gl.luma,
target2: gl
});
}
}
}
function polyfillExtension(gl, _ref2) {
let {
extension,
target,
target2
} = _ref2;
const defaults = WEBGL2_CONTEXT_POLYFILLS[extension];
assert(defaults);
const {
meta = {}
} = defaults;
const {
suffix = ''
} = meta;
const ext = gl.getExtension(extension);
for (const key of Object.keys(defaults)) {
const extKey = "".concat(key).concat(suffix);
let polyfill = null;
if (key === 'meta') {} else if (typeof gl[key] === 'function') {} else if (ext && typeof ext[extKey] === 'function') {
polyfill = function () {
return ext[extKey](...arguments);
};
} else if (typeof defaults[key] === 'function') {
polyfill = defaults[key].bind(target);
}
if (polyfill) {
target[key] = polyfill;
target2[key] = polyfill;
}
}
}
//# sourceMappingURL=polyfill-context.js.map