Modern WebGL state wrapper for PEX: allocate GPU resources (textures, buffers), setup state pipelines and passes, and combine them into commands.
npm install pex-context
import createContext from "pex-context";
import { mat4 } from "pex-math";
import { cube } from "primitive-geometry";
const W = 640;
const H = 480;
const ctx = createContext({ width: W, height: H });
const geom = cube();
const clearCmd = {
pass: ctx.pass({
clearColor: [0.2, 0.2, 0.2, 1],
clearDepth: 1,
}),
};
const drawCmd = {
pipeline: ctx.pipeline({
depthTest: true,
vert: /* glsl */ `
attribute vec3 aPosition;
attribute vec3 aNormal;
uniform mat4 uProjectionMatrix;
uniform mat4 uViewMatrix;
varying vec4 vColor;
void main () {
vColor = vec4(aNormal * 0.5 + 0.5, 1.0);
gl_Position = uProjectionMatrix * uViewMatrix * vec4(aPosition, 1.0);
}
`,
frag: /* glsl */ `
precision highp float;
varying vec4 vColor;
void main() {
gl_FragColor = vColor;
}
`,
}),
attributes: {
aPosition: ctx.vertexBuffer(geom.positions),
aNormal: ctx.vertexBuffer(geom.normals),
},
indices: ctx.indexBuffer(geom.cells),
uniforms: {
uProjectionMatrix: mat4.perspective(
mat4.create(),
Math.PI / 4,
W / H,
0.1,
100,
),
uViewMatrix: mat4.lookAt(mat4.create(), [2, 2, 5], [0, 0, 0], [0, 1, 0]),
},
};
ctx.frame(() => {
ctx.submit(clearCmd);
ctx.submit(drawCmd);
});
object
ctx
Create a context object
PexResource
object
PexResource
PexResource
PexResource
QueryOptions
PexResource
HTMLImageElement
| HTMLVideoElement
| HTMLCanvasElement
WebGLRenderingContext.TEXTURE_2D
| WebGLRenderingContext.TEXTURE_CUBE_MAP
PexResource
PexResource
PexResource
object
object
All resources are plain js object and once constructed their properties can be accessed directly. Please note those props are read only. To set new values or upload new data to GPU see updating resources.
object
object
object
object
object
Array.<number>
[x, y, w, h]
Array.<number>
[r, g, b, a]
Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array
object
Kind: global namespace
object
number
number
PexResource
PexResource
PexResource
PexResource
PexResource
PexResource
PexResource
PexResource
PexResource
Uint8Array
The RenderingContext
returned by pex-gl
Kind: static property of ctx
Max capabilities and extensions availability. See Capabilities Table.
Kind: static property of ctx
number
Getter for gl.drawingBufferWidth
Kind: static property of ctx
number
Getter for gl.drawingBufferHeight
Kind: static property of ctx
Kind: static enum of ctx
Properties
Name | Default |
---|---|
One | gl.ONE |
Zero | gl.ZERO |
SrcAlpha | gl.SRC_ALPHA |
OneMinusSrcAlpha | gl.ONE_MINUS_SRC_ALPHA |
DstAlpha | gl.DST_ALPHA |
OneMinusDstAlpha | gl.ONE_MINUS_DST_ALPHA |
SrcColor | gl.SRC_COLOR |
OneMinusSrcColor | gl.ONE_MINUS_SRC_COLOR |
DstColor | gl.DST_COLOR |
OneMinusDstColor | gl.ONE_MINUS_DST_COLOR |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
PositiveX | gl.TEXTURE_CUBE_MAP_POSITIVE_X |
NegativeX | gl.TEXTURE_CUBE_MAP_NEGATIVE_X |
PositiveY | gl.TEXTURE_CUBE_MAP_POSITIVE_Y |
NegativeY | gl.TEXTURE_CUBE_MAP_NEGATIVE_Y |
PositiveZ | gl.TEXTURE_CUBE_MAP_POSITIVE_Z |
NegativeZ | gl.TEXTURE_CUBE_MAP_NEGATIVE_Z |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
Never | gl.NEVER |
Less | gl.LESS |
Equal | gl.EQUAL |
LessEqual | gl.LEQUAL |
Greater | gl.GREATER |
NotEqual | gl.NOTEQUAL |
GreaterEqual | gl.GEQUAL |
Always | gl.ALWAYS |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
Front | gl.FRONT |
Back | gl.BACK |
FrontAndBack | gl.FRONT_AND_BACK |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
Nearest | gl.NEAREST |
Linear | gl.LINEAR |
NearestMipmapNearest | gl.NEAREST_MIPMAP_NEAREST |
NearestMipmapLinear | gl.NEAREST_MIPMAP_LINEAR |
LinearMipmapNearest | gl.LINEAR_MIPMAP_NEAREST |
LinearMipmapLinear | gl.LINEAR_MIPMAP_LINEAR |
Mapping of ctx.TextureFormat keys to their string values and legacy depth formats
One of:
Kind: static enum of ctx
Kind: static enum of ctx
Properties
Name | Default |
---|---|
RGBA32F |
|
RGBA16F |
|
R16F |
|
RG16F |
|
R32F |
|
RG32F |
|
R11F_G11F_B10F |
|
Kind: static enum of ctx
Properties
Name | Default |
---|---|
Linear | 1 |
Gamma | 2 |
SRGB | 3 |
RGBM | 4 |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
Points | gl.POINTS |
Lines | gl.LINES |
LineStrip | gl.LINE_STRIP |
Triangles | gl.TRIANGLES |
TriangleStrip | gl.TRIANGLE_STRIP |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
StaticDraw | gl.STATIC_DRAW |
DynamicDraw | gl.DYNAMIC_DRAW |
StreamDraw | gl.STREAM_DRAW |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
ClampToEdge | gl.CLAMP_TO_EDGE |
Repeat | gl.REPEAT |
MirroredRepeat | gl.MIRRORED_REPEAT |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
TimeElapsed | gl.TIME_ELAPSED |
AnySamplesPassed | gl.ANY_SAMPLES_PASSED |
AnySamplesPassedConservative | gl.ANY_SAMPLES_PASSED_CONSERVATIVE |
TransformFeedbackPrimitivesWritten | gl.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN |
Kind: static enum of ctx
Properties
Name | Default |
---|---|
Ready | ready |
Active | active |
Pending | pending |
Set the context size and pixelRatio The new size and resolution will not be applied immediately but before drawing the next frame to avoid flickering. Context's canvas doesn't resize automatically, even if you don't pass width/height on init and the canvas is assigned the dimensions of the window. To handle resizing use the following code:
window.addEventListener("resize", () => {
ctx.set({ width: window.innerWidth, height: window.innerHeight });
});
Kind: static method of ctx
Param | Type |
---|---|
options | PexContextSetOptions |
Enable debug mode
Kind: static method of ctx
Param | Type |
---|---|
[enabled] | boolean |
Render Loop
Kind: static method of ctx
Param | Type | Description |
---|---|---|
cb | function |
Request Animation Frame callback |
Submit a command to the GPU. Commands are plain js objects with GPU resources needed to complete a draw call.
const cmd = {
pass: Pass
pipeline: Pipeline,
attributes: { name: VertexBuffer | { buffer: VertexBuffer, offset: number, stride: number } },
indices: IndexBuffer | { buffer: IndexBuffer, offset: number, count: number },
// or
count: number,
instances: number,
uniforms: { name: number, name: Array, name: Texture2D },
viewport: [0, 0, 1920, 1080],
scissor: [0, 0, 1920, 1080]
}
Note: Either indices or count need to be specified when drawing geometry. Note: Scissor region is by default set to null and scissor test disabled.
Kind: static method of ctx
Param | Type |
---|---|
cmd | PexCommand |
[batches] | PexCommand | Array.<PexCommand> |
[subCommand] | PexCommand |
Example
ctx.submit(cmd, opts)
: submit partially updated command without modifying the original one.// Draw mesh with custom color
ctx.submit(cmd, {
uniforms: {
uColor: [1, 0, 0, 0],
},
});
ctx.submit(cmd, [opts1, opts2, opts3...])
: submit a batch of commands differences in opts.// Draw same mesh twice with different material and position
ctx.submit(cmd, [
{ pipeline: material1, uniforms: { uModelMatrix: position1 },
{ pipeline: material2, uniforms: { uModelMatrix: position2 }
])
ctx.submit(cmd, cb)
: submit command while preserving state from another command. This approach allows to simulate state stack with automatic cleanup at the end of callback.// Render to texture
ctx.submit(renderToFboCmd, () => {
ctx.submit(drawMeshCmd);
});
PexResource
Passes are responsible for setting render targets (textures) and their clearing values. FBOs are created internally and automatically.
Kind: static method of ctx
Param | Type |
---|---|
opts | PassOptions |
Example
const pass = ctx.pass({
color: [Texture2D, ...]
color: [{ texture: Texture2D | TextureCube, target: CubemapFace }, ...]
depth: Texture2D
clearColor: Array,
clearDepth: number,
})
PexResource
Pipelines represent the state of the GPU rendering pipeline (shaders, blending, depth test etc).
Kind: static method of ctx
Param | Type |
---|---|
opts | PipelineOptions |
Example
const pipeline = ctx.pipeline({
vert: string,
frag: string,
depthWrite: boolean,
depthTest: boolean,
depthFunc: DepthFunc,
blend: boolean,
blendSrcRGBFactor: BlendFactor,
blendSrcAlphaFactor: BlendFactor,
blendDstRGBFactor: BlendFactor,
blendDstAlphaFactor: BlendFactor,
cullFace: boolean,
cullFaceMode: Face,
colorMask: Array,
primitive: Primitive,
});
PexResource
Create a VAO resource.
Kind: static method of ctx
Param | Type |
---|---|
opts | VertexArrayOptions |
Example
const vertexLayout = {
aPosition: { location: 0, type: "vec3" },
aNormal: { location: 1, type: "vec3" },
};
const drawCmd = {
pipeline: ctx.pipeline({
vertexLayout,
// ...
}),
vertexArray: ctx.vertexArray({
vertexLayout,
attributes: {
aPosition: ctx.vertexBuffer(geom.positions),
aNormal: { buffer: ctx.vertexBuffer(geom.normals) },
},
indices: ctx.indexBuffer(geom.cells),
}),
// ...
};
PexResource
Create a 2D Texture resource.
Kind: static method of ctx
Param | Type |
---|---|
opts | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | TextureOptions |
Example
const tex = ctx.texture2D({
data: [255, 255, 255, 255, 0, 0, 0, 255],
width: 2,
height: 1,
pixelFormat: ctx.PixelFormat.RGB8,
encoding: ctx.Encoding.Linear,
wrap: ctx.Wrap.Repeat,
});
PexResource
Create a 2D Texture cube resource.
Kind: static method of ctx
Param | Type |
---|---|
opts | TextureCubeOptions |
Example
const tex = ctx.textureCube({
data: [posx, negx, posy, negy, posz, negz],
width: 64,
height: 64
])
PexResource
Renderbuffers represent pixel data store for rendering operations.
Kind: static method of ctx
Param | Type |
---|---|
opts | RenderbufferOptions |
Example
const tex = ctx.renderbuffer({
width: 1280,
height: 720,
pixelFormat: ctx.PixelFormat.DEPTH_COMPONENT16,
});
PexResource
Create an attribute buffer (ARRAY_BUFFER) resource. Stores vertex data in the GPU memory.
Kind: static method of ctx
Param | Type |
---|---|
opts | BufferOptions |
Example
const vertexBuffer = ctx.vertexBuffer({
data: Array | TypedArray | ArrayBuffer,
});
PexResource
Create an index buffer (ELEMENT_ARRAY_BUFFER) resource. Stores index data in the GPU memory.
Kind: static method of ctx
Param | Type |
---|---|
opts | BufferOptions |
Example
const indexBuffer = ctx.vertexBuffer({
data: Array | TypedArray | ArrayBuffer,
});
PexResource
Queries can be used for GPU timers.
Kind: static method of ctx
Param | Type |
---|---|
opts | QueryOptions |
Example
const query = ctx.query({
target: QueryTarget,
});
Begin the query measurement.
Kind: static method of ctx
Param | Type | Description |
---|---|---|
query | PexQuery |
Note: There can be only one query running at the time. |
End the query measurement.
Kind: static method of ctx
Param | Type | Description |
---|---|---|
query | PexQuery |
Note: The result is not available immediately and will be null until the state changes from ctx.QueryState.Pending to ctx.QueryState.Ready . |
Uint8Array
Helper to read a block of pixels from a specified rectangle of the current color framebuffer.
Kind: static method of ctx
Param | Type |
---|---|
viewport | Object |
Update a resource.
Kind: static method of ctx
Param | Type |
---|---|
resource | PexResource |
opts | object |
Example
ctx.update(buffer, { data: [] });
ctx.update(texture, {
width: 1,
height: 1,
data: new Uint8Array([255, 0, 0, 255]),
});
Delete one or all resource(s). Disposed resources are no longer valid for use.
Kind: static method of ctx
Param | Type |
---|---|
[resource] | PexResource |
Example Delete all allocated resources:
ctx.dispose();
Delete a single resource:
ctx.dispose(texture);
Note: Framebuffers are ref counted and released by Pass. Programs are also ref counted and released by Pipeline.
ctx
Create a context object
Kind: global function
Param | Type |
---|---|
[options] | PexContextOptions | module:pex-gl~Options |
PexResource
Kind: global typedef Properties
Name | Type | Default |
---|---|---|
data | Array | TypedArray | ArrayBuffer |
|
[type] | ctx.DataType |
|
[usage] | Usage |
ctx.Usage.StaticDraw |
offset | number |
object
Kind: global typedef Properties
Name | Type |
---|---|
texture | PexResource |
target | WebGLRenderingContext.FRAMEBUFFER |
PexResource
Kind: global typedef Properties
Name | Type | Description |
---|---|---|
[color] | Array.<PexTexture2D> | Array.<Attachment> |
render target |
[depth] | PexTexture2D |
render target |
[clearColor] | Color |
|
[clearDepth] | number |
PexResource
Kind: global typedef Properties
Name | Type | Default | Description |
---|---|---|---|
[vert] | string |
null |
Vertex shader code |
[frag] | string |
null |
Fragment shader code |
[depthWrite] | boolean |
true |
Depth write mask |
[depthTest] | boolean |
false |
Depth test on/off |
[depthFunc] | DepthFunc |
ctx.DepthFunc.LessEqual |
Depth test function |
[blend] | boolean |
false |
Blending on/off |
[blendSrcRGBFactor] | BlendFactor |
ctx.BlendFactor.One |
Blending source color factor |
[blendSrcAlphaFactor] | BlendFactor |
ctx.BlendFactor.One |
Blending source alpha factor |
[blendDstRGBFactor] | BlendFactor |
ctx.BlendFactor.One |
Blending destination color factor |
[blendDstAlphaFactor] | BlendFactor |
ctx.BlendFactor.One |
Blending destination alpha factor |
[cullFace] | boolean |
false |
Face culling on/off |
[cullFaceMode] | Face |
ctx.Face.Back |
Face culling mode |
[colorMask] | Array.<boolean> |
[true, true, true, true] |
Color write mask for [r, g, b, a] |
[primitive] | Primitive |
ctx.Primitive.Triangles |
Geometry primitive |
PexResource
Kind: global typedef Properties
Name | Type | Default | Description |
---|---|---|---|
[target] | QueryTarget |
ctx.QueryTarget.TimeElapsed |
query type |
QueryOptions
Kind: global typedef Properties
Name | Type | Default | Description |
---|---|---|---|
[state] | QueryState |
ctx.QueryState.Ready |
|
[result] | number |
result of the measurement |
PexResource
Kind: global typedef Properties
Name | Type | Default | Description |
---|---|---|---|
width | number |
||
height | number |
||
[pixelFormat] | PixelFormat |
ctx.PixelFormat.DEPTH_COMPONENT16 |
only PixelFormat.DEPTH_COMPONENT16 is currently supported for use as render pass depth storage (e.g. ctx.pass({ depth: renderbuffer }) ) for platforms with no WEBGL_depth_texture support. |
HTMLImageElement
| HTMLVideoElement
| HTMLCanvasElement
Kind: global typedef Properties
Name | Type |
---|---|
data | Array | TypedArray |
width | number |
height | number |
WebGLRenderingContext.TEXTURE_2D
| WebGLRenderingContext.TEXTURE_CUBE_MAP
PexResource
Kind: global typedef Properties
Name | Type | Default | Description |
---|---|---|---|
[data] | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | Array | TypedArray | TextureOptionsData | Array.<HTMLImageElement> | Array.<TextureOptionsData> |
||
[width] | number |
||
[height] | number |
||
[pixelFormat] | PixelFormat |
ctx.PixelFormat.RGB8 |
|
[internalFormat] | ctx.TextureFormat |
ctx.TextureFormat.RGBA |
|
[type] | ctx.DataType |
ctx.TextureFormat[opts.pixelFormat] |
|
[encoding] | Encoding |
ctx.Encoding.Linear |
|
[wrapS] | Wrap |
ctx.Wrap.ClampToEdge |
|
[wrapT] | Wrap |
ctx.Wrap.ClampToEdge |
|
[wrap] | Wrap |
ctx.Wrap.ClampToEdge |
|
[min] | Filter |
ctx.Filter.Nearest |
|
[mag] | Filter |
ctx.Filter.Nearest |
|
[aniso] | number |
0 |
requires EXT_texture_filter_anisotropic |
[mipmap] | boolean |
true |
requires min to be set to ctx.Filter.LinearMipmapLinear or similar |
[premultiplyAlpha] | boolean |
false |
|
[flipY] | boolean |
false |
|
[compressed] | boolean |
false |
|
[target] | TextureTarget |
PexResource
Kind: global typedef
Extends: TextureOptions
Properties
Name | Type | Description |
---|---|---|
[data] | Array.<HTMLImageElement> | Array.<TypedArray> |
6 images, one for each face +X, -X, +Y, -Y, +Z, -Z |
PexResource
Kind: global typedef Properties
Name | Type |
---|---|
vertexLayout | object |
[attributes] | object |
[indices] | object |
object
Kind: global typedef Properties
Name | Type | Default |
---|---|---|
[gl] | WebGLRenderingContext | WebGL2RenderingContext |
WebGL2RenderingContext |
[width] | number |
window.innerWidth |
[height] | number |
window.innerHeight |
[pixelRatio] | number |
1 |
[type] | "webgl" | "webgl2" |
"webgl2" |
[debug] | boolean |
false |
object
All resources are plain js object and once constructed their properties can be accessed directly. Please note those props are read only. To set new values or upload new data to GPU see updating resources.
Kind: global typedef Properties
Name | Type |
---|---|
name | string |
object
object
Kind: global typedef Properties
Name | Type | Description |
---|---|---|
buffer | object |
ctx.vertexBuffer() or ctx.indexBuffer() |
[offset] | number |
|
[stride] | number |
|
[divisor] | number |
|
[normalized] | boolean |
object
Kind: global typedef Properties
Name | Type | Description |
---|---|---|
pass | PassOptions |
|
pipeline | PipelineOptions |
|
[attributes] | object |
vertex attributes, map of attributeName: ctx.vertexBuffer() or attributeName: PexAttribute |
[indices] | object |
indices, ctx.indexBuffer() or PexAttribute |
[count] | number |
number of vertices to draw |
[instances] | number |
number instances to draw |
[uniforms] | object |
shader uniforms, map of name: value |
[viewport] | Viewport |
drawing viewport bounds |
[scissor] | Viewport |
scissor test bounds |
[multiDraw] | MultiDrawOptions |
|
[baseVertex] | number |
|
[baseInstance] | number |
object
Kind: global typedef See
Properties
Name | Type |
---|---|
counts | Int32Array | Array |
[countsOffset] | number |
offsets | Int32Array | Array |
[offsetsOffset] | number |
firsts | Int32Array | Array |
[firstsOffset] | number |
instanceCounts | Int32Array | Array |
[instanceCountsOffset] | number |
baseVertices | Int32Array | Array |
[baseVerticesOffset] | number |
baseInstances | UInt32Array | Array |
[baseInstancesOffset] | number |
[drawCount] | number |
object
Kind: global typedef Properties
Name | Type |
---|---|
[width] | number |
[height] | number |
[pixelRatio] | number |
Array.<number>
[x, y, w, h]
Array.<number>
[r, g, b, a]
Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array
Kind: global typedef
Example
const maxTextureSize = ctx.capabilities.maxTextureSize;
Name | Type |
---|---|
isWebGL2 |
number |
maxColorAttachments |
number |
maxTextureImageUnits |
number |
maxVertexTextureImageUnits |
number |
maxVertexAttribs |
number |
maxTextureSize |
number |
maxCubeMapTextureSize |
number |
depthTexture |
boolean |
shaderTextureLod |
boolean |
textureFloat |
boolean |
textureFloatLinear |
boolean |
textureHalfFloat |
boolean |
textureHalfFloatLinear |
boolean |
textureFilterAnisotropic |
boolean |
disjointTimerQuery |
boolean |
colorBufferFloat |
boolean |
colorBufferHalfFloat |
boolean |
floatBlend |
boolean |
multiDraw |
boolean |
drawInstancedBase |
boolean |
multiDrawInstancedBase |
boolean |
MIT. See license file.