@thi.ng/webgl
Version:
WebGL & GLSL abstraction layer
93 lines (92 loc) • 2.48 kB
JavaScript
import { isArray } from "@thi.ng/checks/is-array";
import { GLSLVersion } from "@thi.ng/shader-ast-glsl/api";
const PREFIXES = {
a: "a_",
v: "v_",
u: "u_",
o: "o_"
};
const NO_PREFIXES = {
a: "",
v: "",
u: "",
o: ""
};
const SYNTAX = {
/**
* WebGL (GLSL ES 1.0)
*/
[GLSLVersion.GLES_100]: {
number: 100,
attrib: (id, type, pre) => `attribute ${isArray(type) ? type[0] : type} ${pre.a}${id};`,
varying: {
vs: (id, type, pre) => __arrayDecl("varying", type, pre.v + id),
fs: (id, type, pre) => __arrayDecl("varying", type, pre.v + id)
},
uniform: (id, u, pre) => __arrayDecl("uniform", u, pre.u + id),
output: (id, type, pre) => isArray(type) ? `#define ${pre.o}${id} gl_FragData[${type[1]}]` : ""
},
/**
* WebGL 2 (GLSL ES 3)
*/
[GLSLVersion.GLES_300]: {
number: 300,
attrib: (id, type, pre) => isArray(type) ? `layout(location=${type[1]}) in ${type[0]} ${pre.a}${id};` : `in ${type} ${pre.a}${id};`,
varying: {
vs: (id, type, pre) => __arrayDecl("out", type, pre.v + id),
fs: (id, type, pre) => __arrayDecl("in", type, pre.v + id)
},
uniform: (id, u, pre) => __arrayDecl("uniform", u, pre.u + id),
output: (id, type, pre) => isArray(type) ? `layout(location=${type[1]}) out ${type[0]} ${pre.o}${id};` : `out ${type} ${pre.o}${id};`
}
};
const __arrayDecl = (qualifier, decl, id) => {
const type = isArray(decl) ? decl[0] : decl;
return type.indexOf("[]") > 0 ? `${qualifier} ${type.replace("[]", "")} ${id}[${decl[1]}];` : `${qualifier} ${type} ${id};`;
};
const VERSION_CHECK = (ver, ok, fail = "") => {
let cmp = ">=";
if (!ok) {
ok = fail;
fail = null;
cmp = "<";
}
return `#if __VERSION__ ${cmp} ${ver}
${ok}${fail ? `
#else
${fail}` : ""}
#endif`;
};
const ALIAS_TEXTURE = VERSION_CHECK(
300,
"",
"#define texture texture2D"
);
const EXPORT_FRAGCOL = (body = "col", out = "o_fragColor") => VERSION_CHECK(300, `${out}=${body};`, `gl_FragColor=${body};`);
const GLSL_HEADER = `#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp int;
precision highp float;
#else
precision mediump int;
precision mediump float;
#endif
${VERSION_CHECK(300, "precision lowp sampler3D;")}
#ifndef PI
#define PI 3.141592653589793
#endif
#ifndef TAU
#define TAU 6.283185307179586
#endif
#ifndef HALF_PI
#define HALF_PI 1.570796326794896
#endif
`;
export {
ALIAS_TEXTURE,
EXPORT_FRAGCOL,
GLSL_HEADER,
NO_PREFIXES,
PREFIXES,
SYNTAX,
VERSION_CHECK
};