>  기사  >  웹 프론트엔드  >  WebGL 삼각형 설정 분석

WebGL 삼각형 설정 분석

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-11 10:44:02967검색

WebGL은 Javascript의 보다 복잡한 API 중 하나로 기록되어 있습니다. 대화형 모든 것에 흥미를 느끼는 웹 개발자로서 저는 WebGL의 MDN 문서를 자세히 살펴보기로 결정했습니다. 저는 WebGL의 많은 어려움을 추상화하는 Three.js로 작업해 보았지만, 그 내용을 공개하지 않을 수 없었습니다!

이 심층 분석의 목표는 문서를 더 간단한 용어로 설명할 수 있을 만큼 문서를 이해할 수 있는지 확인하는 것이었습니다. 면책조항 — 저는 Three.js로 작업해 왔으며 3D 그래픽 용어와 패턴에 대해 약간의 지식을 가지고 있습니다. 이러한 개념이 어떤 식으로든 적용된다면 반드시 설명하겠습니다.

먼저 삼각형을 만드는 데 집중하겠습니다. 그 이유는 webGL 설정에 필요한 부분에 대한 이해를 돕기 위함입니다.

어떤 내용이 다루어질지 알아보기 위해 우리가 거치게 될 단계는 다음과 같습니다.

  • HTML 캔버스 설정

  • WebGL 컨텍스트 가져오기

  • 캔버스 색상을 지우고 새 색상으로 설정

  • 삼각형 (x,y) 좌표 배열 만들기

  • 정점 및 조각 셰이더 코드 추가

  • 셰이더 코드 처리 및 컴파일

  • webGL 프로그램 만들기

  • 버퍼 생성 및 webGL 프로그램 바인딩

  • 프로그램 이용하기

  • GPU 정보를 CPU에 연결

  • 삼각형 그리기

HTML 캔버스 설정

  1. "RenderTriangle"이라는 폴더를 만듭니다
  2. 해당 폴더에 index.html과 main.js 파일을 생성하세요

index.html 파일 내에 다음 코드를 추가하세요.

index.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="main.js"></script>
</html>
  1. 은 WebGL 컨텍스트 렌더링을 위한 진입점입니다

  2. 기본 HTML 코드를 설정하고 main.js 파일을 링크합니다.

  3. main.js 파일에서 webGL 콘텐츠를 렌더링하기 위해 캔버스 ID에 액세스합니다.

HTML 캔버스 준비

main.js 파일 내에 HTML 캔버스를 준비하는 다음 코드를 추가하세요.

main.js

// get canvas
const canvas = document.getElementById("canvas");

// set width and height of canvas
canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

// get the webgl context
const gl = canvas.getContext("webgl2");
  1. ID로 HTML 캔버스를 가져와서 "canvas"라는 변수에 저장합니다(어떤 이름이든 사용할 수 있음).

  2. window.innerWidthwindow.innerHeight에 액세스하여 캔버스의 canvas.widthcanvas.height 속성을 ​​설정합니다. . 이렇게 하면 렌더링된 디스플레이가 브라우저 창의 크기로 설정됩니다.

  3. canvas.getContext(“webgl2”)를 사용하여 WebGL 컨텍스트를 가져와서 “gl”이라는 변수에 저장합니다.

클리어 컬러

main.js

gl.clearColor(0.1, 0.2, 0.3, 1.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);

webGL 프로그램을 작성하기 전에 캔버스의 배경색을 설정해야 합니다. WebGL에는 이를 실현하는 두 가지 방법이 있습니다.

clearColor() — 특정 배경색을 설정하는 메서드입니다. WebGL을 HTML 캔버스에 렌더링할 때 CSS가 배경을 검정색으로 설정하기 때문에 "clearColor"라고 합니다. clearColor()를 호출하면 기본 색상이 지워지고 원하는 색상이 설정됩니다. 아래에서 확인할 수 있습니다.

참고: clearColor()에는 4개의 매개변수(r, g, b, a)가 있습니다

clear()clearColor()가 호출되고 명시적인 배경색이 설정된 후
**clear()**는 버퍼를 사전 설정된 값으로 "지우거나 재설정"하기 위해 호출되어야 합니다(버퍼는 색상 및 깊이 정보를 위한 임시 저장소입니다).

clear() 메소드는 그리기 메소드 중 하나로 실제로 색상을 렌더링하는 메소드입니다. clear() 메서드를 호출하지 않으면 캔버스에 clearColor가 표시되지 않습니다. clear() 매개변수 옵션은
gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT 또는 gl.STENCIL_BUFFER_BIT입니다.

아래 코드에서는 여러 매개변수를 추가하여 다양한 시나리오에서 재설정할 수 있습니다.

  1. gl.DEPTH_BUFFER_BIT — 픽셀 깊이 정보에 대한 버퍼를 나타냅니다

  2. gl.COLOR_BUFFER_BIT — 픽셀 색상 정보에 대한 버퍼를 나타냅니다

삼각형 좌표 설정

main.js

// set position coordinates for shape
const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];

배경이 설정되면 삼각형을 만드는 데 필요한 좌표를 설정할 수 있습니다. 좌표는 (x, y) 좌표로 배열에 저장됩니다.

아래 배열은 3점 좌표를 담고 있습니다. 이 점들이 연결되어 삼각형을 형성합니다.

0.0, -1.0
0.0 , 1.0
1.0, 1.0

정점 및 조각 셰이더 추가

main.js

const vertexShader = `#version 300 es
precision mediump float;

in vec2 position;

void main() {
 gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w
}
`;


const fragmentShader = `#version 300 es
precision mediump float;

out vec4 color;

void main () {
 color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a
}
`;

삼각형 좌표에 대한 변수를 생성한 후 셰이더를 설정할 수 있습니다.

A shader is a program written in OpenGL ES Shading Language. The program takes position and color information about each vertice point. This information is what’s needed to render geometry.

There are two types of shaders functions that are needed to draw webgl content, the vertex shader and fragment shader

*vertex shader *— The vertex shader function uses position information to render each pixel. Per every render, the vertex shader function runs on each vertex. The vertex shader then transforms each vertex from it’s original coordinates to WebGL coordinates. Each transformed vertex is then saved to the gl_Position variable in the vertex shader program.

*fragment shader *— The fragment shader function is called once for every pixel on a shape to be drawn. This occurs after the vertex shader runs. The fragment shader determines how the color of each pixel and “texel (pixel within a texture)” should be applied. The fragment shader color is saved in the gl_FragColor variable in the fragment shader program.

In the code above we are creating both a vertexShader and fragmentShader constant and storing the shader code in them. The Book of Shaders is a great resource for learning how to write GLSL code.

Processing the Vertex and Fragment Shaders

main.js

// process vertex shader
const shader = gl.createShader(gl.VERTEX_SHADER);

gl.shaderSource(shader, vertexShader);

gl.compileShader(shader);

if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log(gl.getShaderInfoLog(vertexShader));
}


// process fragment shader
const shader = gl.createShader(gl.FRAGMENT_SHADER);

gl.shaderSource(shader, fragmentShader);

gl.compileShader(shader);

if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log(gl.getShaderInfoLog(fragmentShader));
}

Now that we wrote the shader code (GLSL), we need to create the shader. The shader code still needs to compile. To do this we call the following functions:

createShader() — This creates the shader within the WebGL context

shaderSource() — This takes the GLSL source code that we wrote and sets it into the webGLShader object that was created with createShader.

compileShader() — This compiles the GLSL shader program into data for the WebGLProgram.

The code above processes the vertex and fragment shaders to eventually compile into the WebGLProgram.

Note: An if conditional is added to check if both shaders have compiled properly. If not, an info log will appear. Debugging can be tricky in WebGL so adding these checks is a must.

Creating a WebGL Program

main.js

const program = gl.createProgram();

// Attach pre-existing shaders
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);

gl.linkProgram(program);

if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  const info = gl.getProgramInfoLog(program);
  throw "Could not compile WebGL program. \n\n${info}";
}

Let’s review the code above:

After compiling the vertexShader and fragmentShader, we can now create a WebGLProgram. A WebGLProgram is an object that holds the compiled vertexShader and fragmentShader.

createProgram() — Creates and initializes the WebGLProgram

attachShader() — This method attaches the shader to the webGLProgram

linkProgram() — This method links the program object with the shader objects

Lastly, we need to make a conditional check to see if the program is running properly. We do this with the gl.getProgramParameter.

Create and Bind the Buffers

Now that the WebGL Program is created and the shader programs are linked to it, it’s time to create the buffers. What are buffers?

To simplify it as much as possible, buffers are objects that store vertices and colors. Buffers don’t have any methods or properties that are accessible. Instead, the WebGL context has it’s own methods for handling buffers.

Buffer — “a temporary storage location for data that’s being moved from one place to another”
-wikipedia

We need to create a buffer so that we can store our triangle colors and vertices.

To do this we add the following:

main.js

const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW);

gl.bindBuffer(gl.ARRAY_BUFFER, null);

In the code above we’re creating a buffer (or temporary storage object) using the createBuffer() method. Then we store it in a constant. Now that we have a buffer object we need to bind it to a target. There are several different target but since we’re storing coordinates in an array we will be using the gl.ARRAY_BUFFER.

To bind the buffer to a target, we use gl.bindBuffer() and pass in the gl.ARRAY_BUFFER (target) and the buffer itself as parameters.

The next step would be to use gl.bufferData() which creates the data store. gl.bufferData() takes the following parameters:

targetgl.ARRAY_BUFFER
datanew Float32Array(triangleCoords)
usage (draw type) — gl.STATIC_DRAW

Lastly, we unbind the buffer from the target to reduce side effects.

Use Program

main.js

gl.useProgram(program);

Once the buffer creation and binding is complete, we can now call the method that sets the WebGLProgram to the rendering state.

Link GPU and CPU

As we get closer to the final step, we need to talk about attributes.

In WebGL, vertex data is stored in a special variable called attributes. attributes are only available to the javascript program and the vertex shader. To access the attributes variable we need to first get the location of the attributes from the GPU. The GPU uses an index to reference the location of the attributes.

main.js

// get index that holds the triangle position information
const position = gl.getAttribLocation(obj.program, obj.gpuVariable);

gl.enableVertexAttribArray(position);

gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

gl.vertexAttribPointer(position, 2, gl.FLOAT, obj.normalize, obj.stride, obj.offset);

Let’s review the code above:

Since we’re rendering a triangle we need the index of the position variable that we set in the vertex shader. We do this using the gl.getAttribLocation() method. By passing in the WebGL program and the position variable name (from the vertex shader) we can get the position attribute’s index.

Next, we need to use the gl.enableVertexAttribArray() method and pass in the position index that we just obtained. This will enable the attributes` storage so we can access it.

We will then rebind our buffer using gl.bindBuffer() and pass in the gl.ARRAY_BUFFER and buffer parameters (the same as when we created the buffers before). Remember in the “Create and Bind the Buffers” section we set the buffer to null to avoid side effects.

When we binded the buffer to the gl.ARRAY_BUFFER we are now able to store our attributes in a specific order. gl.vertexAttribPointer() allows us to do that.

By using gl.vertexAttribPointer() we can pass in the attributes we’d like to store in a specific order. The parameters are ordered first to last.

The gl.vertexAttribPointer is a more complex concept that may take some additional research. You can think of it as a method that allows you to store your attributes in the vertex buffer object in a specific order of your choosing.

Sometimes 3D geometry already has a certain format in which the geometry information is set. vertexAttribPointer comes in handy if you need to make modifications to how that geometry information is organized.

Draw Triangle

main.js

gl.drawArrays(gl.TRIANGLES, 0, 3);

Lastly, we can use the gl.drawArrays method to render the triangle. There are other draw methods, but since our vertices are in an array, this method should be used.

gl.drawArrays() takes three parameters:

mode — which specifies the type of primitive to render. (in this case were rendering a triangle)

first — specifies the starting index in the array of vector points (our triangle coordinates). In this case it’s 0.

count — specifies the number of indices to be rendered. ( since it's a triangle we’re rendering 3 indices)

Note: For more complex geometry with a lot of vertices you can use **triangleCoords.length / 2 **to ****get how many indices your geometry has.

Finally, your triangle should be rendered to the screen! Let’s review the steps.

Breaking Down the WebGL Triangle Setup

  • Set up the HTML canvas

  • Get the WebGL context

  • Clear the canvas color and set a new one

  • Create an array of triangle (x,y )coordinates

  • Add vertex and fragment shader code

  • Process and compile the shader code

  • Create a webGL program

  • Create and bind buffers to the webGL program

  • Use the program

  • Link the GPU information to the CPU

  • Draw out the triangle

The API is a complex one so there’s still a lot to learn but understanding this setup has given me a better foundation.

// Set up the HTML canvas
const canvas = document.getElementById("canvas");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// get the webgl context
const gl = canvas.getContext("webgl2");

// Clear the canvas color and set a new one
gl.clearColor(0.1, 0.2, 0.3, 1.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);


// Create an array of triangle (x,y )coordinates
const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];

// Add vertex and fragment shader code
const vertexShader = `#version 300 es
precision mediump float;
in vec2 position;

void main() {
gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w
}
`;

const fragmentShader = `#version 300 es
precision mediump float;
out vec4 color;

void main () {
color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a
}
`;


// Process and compile the shader code
const vShader = gl.createShader(gl.VERTEX_SHADER);

gl.shaderSource(vShader, vertexShader);
gl.compileShader(vShader);

if (!gl.getShaderParameter(vShader, gl.COMPILE_STATUS)) {
 console.log(gl.getShaderInfoLog(vertexShader));
}


const fShader = gl.createShader(gl.FRAGMENT_SHADER);

gl.shaderSource(fShader, fragmentShader);
gl.compileShader(fShader);

if (!gl.getShaderParameter(fShader, gl.COMPILE_STATUS)) {
console.log(gl.getShaderInfoLog(fragmentShader));
}

// Create a webGL program
const program = gl.createProgram();


// Link the GPU information to the CPU
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);

gl.linkProgram(program);


if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const info = gl.getProgramInfoLog(program);
throw "Could not compile WebGL program. \n\n${info}";
}


// Create and bind buffers to the webGL program
const buffer = gl.createBuffer();

gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);


// Use the program
gl.useProgram(program);



// Link the GPU information to the CPU
const position = gl.getAttribLocation(program, "position");

gl.enableVertexAttribArray(position);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(position, 2, gl.FLOAT, gl.FALSE, 0, 0);


// render triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);

Here are some invaluable references to help understand this material better.

https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
https://www.udemy.com/course/webgl-internals/
https://webglfundamentals.org/

위 내용은 WebGL 삼각형 설정 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.