惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

WebGL Fundamentals

WebGL Using 2 or More Textures WebGL Implementing DrawImage WebGL 2D Matrices WebGL Implementing A Matrix Stack WebGL 2D Rotation WebGL 2D Scale WebGL 2D Translation WebGL - Rasterization vs 3D libraries WebGL 3D - Cameras WebGL 3D Geometry - Lathe WebGL 3D - Directional Lighting WebGL 3D - Point Lighting WebGL 3D - Normal Mapping WebGL 3D - Spot Lighting WebGL - Orthographic 3D WebGL 3D Perspective Correct Texture Mapping WebGL 3D Perspective WebGL Textures WebGL and Alpha WebGL - Animation WebGL Anti-Patterns WebGL Boilerplate WebGL - Cross Origin Images WebGL Cross Platform Issues WebGL Cubemaps WebGL 3D - Data Textures WebGL - Drawing Multiple Things WebGL Drawing Without Data WebGL Environment Maps (reflections) WebGL Fog WebGL Framebuffers WebGL Fundamentals WebGL GPGPU WebGL How It Works WebGL Image Processing Continued WebGL Image Processing WebGL Indexed Vertices WebGL Optimization - Instanced Drawing WebGL - Less Code, More Fun WebGL Load Obj with Mtl WebGL Load Obj WebGL Matrices vs Math Matrices WebGL Multiple Views, Multiple Canvases WebGL Picking WebGL Planar and Perspective Projection Mapping WebGL Points, Lines, and Triangles WebGL Post Processing WebGL Precision Issues WebGL Pulling Vertices Accessing textures by pixel coordinate in WebGL2 A simple way to show the load on the GPU's vertex and fragment processing? Apply a displacement map and specular map Can anyone explain what this GLSL fragment shader is doing? Can I mute the warning about vertex attrib 0 being disabled? Create image warping effect in WebGL Creating a smudge/liquify effect How to draw Depth Sprites Determine min/max values for the entire image Don't blend a polygon that crosses itself Drawing 2D image with depth map to achieve pseudo-3D effect Drawing a heightmap Drawing layers with different points Drawing Many different models in a single draw call Drawing textured sprites with instanced drawing Efficient particle system in javascript? (WebGL) Emulating palette based graphics in WebGL FPS-like camera movement with basic matrix transformations Get the size of a point for collision checking GLSL shader to support coloring and texturing How can I compute for 500 points which of 1000 line segments is nearest to each point? How can I create a 16bit historgram of 16bit data How can I get all the uniforms and uniformBlocks How can I move the perspective vanishing point from the center of the canvas? How to Achieve Moving Line with Trail Effects How to bind an array of textures to a WebGL shader uniform? How to blend colors across 2 triangles How to combine more text drawing into fewer draw calls How to control the color between vertices How to create a torus How to detect clipped triangles in the framgment shader How to determine the average brightness in a scene? How to draw correctly textured trapezoid polygons How to fade the drawing buffer How to figure out how much GPU work to do without crashing WebGL How to get audio data into a shader How to get code completion for WebGL in Visual Studio Code How to get the 3d coordinates of a mouse click How to get pixelize effect in webgl? How to implement zoom from mouse in 2D WebGL How to import a heightmap in WebGL How to load images in the background with no jank How to make a smudge brush tool How to make WebGL canvas transparent How to optimize rendering a UI How to prevent texture bleeding with a texture atlas How to process particle positions How to read a single component with readPixels How to render large scale images like 32000x32000 How to simulate a 3D texture in WebGL How to support both WebGL and WebGL2
WebGL Attributes
WebGLFundame · 2025-02-26 · via WebGL Fundamentals

This article is meant to try to give you a mental image of how attribute state is setup in WebGL. There is a similar article on texture units.

As a prerequisite you probably want to read How WebGL Works and WebGL Shaders and GLSL.

Attributes

In WebGL attributes are inputs to a vertex shader that get their data from buffers. WebGL will execute a user supplied vertex shader N times when either gl.drawArrays or gl.drawElements is called. For each iteration the attributes define how to pull the data out of the buffers bound to them and supply them to the attributes inside the vertex shader.

If they were implemented in JavaScript they would look something like this

// pseudo code
const gl = {
  arrayBuffer: null,
  vertexArray: {
    attributes: [
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
      { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?, divisor: 0, },
    ],
    elementArrayBuffer: null,
  },
}

As you can see above there are 8 attributes.

When you call gl.enableVertexAttribArray(location) or gl.disableVertexAttribArray you can think of it like this

// pseudo code
gl.enableVertexAttribArray = function(location) {
  const attrib = gl.vertexArray.attributes[location];
  attrib.enable = true;
};

gl.disableVertexAttribArray = function(location) {
  const attrib = gl.vertexArray.attributes[location];
  attrib.enable = false;
};

In other words location directly refers to the index of an attribute.

Similarly gl.vertexAttribPointer is used to set almost all the rest of an attribute's settings. It would be implemented something like this

// pseudo code
gl.vertexAttribPointer = function(location, size, type, normalize, stride, offset) {
  const attrib = gl.vertexArray.attributes[location];
  attrib.size = size;
  attrib.type = type;
  attrib.normalize = normalize;
  attrib.stride = stride ? stride : sizeof(type) * size;
  attrib.offset = offset;
  attrib.buffer = gl.arrayBuffer;  // !!!! <-----
};

Notice that when we call gl.vertexAttribPointer, attrib.buffer is set to whatever the current gl.arrayBuffer is set to. gl.arrayBuffer in the pseudo code above would be set by calling gl.bindBuffer(gl.ARRAY_BUFFER, someBuffer).

// pseudo code
gl.bindBuffer = function(target, buffer) {
  switch (target) {
    case ARRAY_BUFFER:
      gl.arrayBuffer = buffer;
      break;
    case ELEMENT_ARRAY_BUFFER;
      gl.vertexArray.elementArrayBuffer = buffer;
      break;
  ...
};

So, next up we have vertex shaders. In vertex shader you declare attributes. Example:

attribute vec4 position;
attribute vec2 texcoord;
attribute vec3 normal;

...

void main() {
  ...
}

When you link a vertex shader with a fragment shader by calling gl.linkProgram(someProgram) WebGL (the driver/GPU/browser) decide on their own which index/location to use for each attribute. Unless you manually assign locations (see below) you have no idea which ones they're going to pick. It's up to the browser/driver/GPU. So, you have to ask it which attribute did you use for position, texcoord, and normal?. You do this by calling gl.getAttribLocation

const positionLoc = gl.getAttribLocation(program, 'position');
const texcoordLoc = gl.getAttribLocation(program, 'texcoord');
const normalLoc = gl.getAttribLocation(program, 'normal');

Let's say positionLoc = 5. That means when the vertex shader executes (when you call gl.drawArrays orgl.drawElements) the vertex shader expects you to have setup attribute 5 with the correct type, size, offset, stride, buffer etc.

Note that BEFORE you link the program you can choose the locations by calling gl.bindAttribLocation(program, location, nameOfAttribute). Example:

// Tell `gl.linkProgram` to assign `position` to use attribute #7
gl.bindAttribLocation(program, 7, 'position');

Full Attribute State

Missing from the description above is that each attribute also has a default value. It is left out above because it is uncommon to use it.

attributeValues: [
  [0, 0, 0, 1],
  [0, 0, 0, 1],
  ...
],
vertexArray: {
  attributes: [
   { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?,
    divisor: 0, },
   { enable: ?, type: ?, size: ?, normalize: ?, stride: ?, offset: ?, buffer: ?,
    divisor: 0, },
   ...

You can set each attribute's value with the various gl.vertexAttribXXX functions. The value is used when enable is false. When enable is true, data for the attribute is pulled from the assigned buffer.

Vertex Array Objects (VAO)s

WebGL has an extension, OES_vertex_array_object

In the diagram above the OES_vertex_array_object extension lets you create and replace the vertexArray. In other words

const vao = ext.createVertexArrayOES();

creates the object you see attached to gl.vertexArray in the pseudo code above. Calling ext.bindVertexArrayOES(vao) assigns your created vertex array object as the current vertex array.

// pseudo code
ext.bindVertexArrayOES = function(vao) {
  gl.vertexArray = vao ? vao : defaultVAO;
};

This lets you set all of the attributes and the ELEMENT_ARRAY_BUFFER in the current VAO so that when you want to draw a particular shape it's one call to ext.bindVertexArrayOES to effectively setup all attributes where as without the extension it would be up to one call to both gl.bindBuffer, gl.vertexAttribPointer (and possibly gl.enableVertexAttribArray) per attribute.

You can see it's arguably a good thing to use vertex array objects. To use them though often requires more organization. For example let's stay you want to draw a cube with gl.TRIANGLES with one shader and then again with gl.LINES with a different shader. Let's say when you draw with triangles you use normals for lighting so you declare attributes in your shader like this:

// lighting-shader
// shader for cube drawn with triangles

attribute vec4 a_position;
attribute vec3 a_normal;

You then use those positions and normals like we covered in the first article on lighting

For the lines you don't want lighting, you want a solid color so you do something similar to the first shaders on the first page of these tutorials. You declare a uniform for color. That means in your vertex shader you only need position

// solid-shader
// shader for cube with lines

attribute vec4 a_position;

We have no idea what attribute locations will be decided for each shader. Let's assume for lighting-shader above the locations are

a_position location = 1
a_normal location = 0

and for the solid-shader which only has one attribute it's

a_position location = 0

It's clear when switching shaders we'll need to setup our attributes differently. One shader expects a_position's data to appear on attribute 0. The other shader expects it to appear on attribute 1.

Resetting up the attributes is extra work. Worse, the entire point of using a vertex array object is to save us not having to do that work. To fix this issue we'd bind the locations before linking the shader programs.

We'd tell WebGL

gl.bindAttribLocation(solidProgram, 0, 'a_position');
gl.bindAttribLocation(lightingProgram, 0, 'a_position');
gl.bindAttribLocation(lightingProgram, 1, 'a_normal');

BEFORE calling gl.linkProgram. This tells WebGL which locations to assign when linking the shader. Now we can use the same VAO for both shaders.

Maximum Attributes

WebGL requires that at least 8 attributes are supported but a particular computer/browser/implementation/driver can support more. You can find out how many are supported by calling

const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);

If you decide to use more than 8 you probably want to check how many are actually supported and inform the user if their machine doesn't have enough or else fallback to simpler shaders.

State Diagram

If all of this is hard to follow this state diagram might help visualize what's happening.