/
ZFighting.html
96 lines (80 loc) · 2.81 KB
/
ZFighting.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="./lib/cuon-matrix.js"></script>
</head>
<body>
<canvas id="webgl" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('webgl')
const gl = canvas.getContext('webgl')
const VSHADER_SOURCE = `
attribute vec4 a_Position;
attribute vec4 a_Color;
uniform mat4 u_mvpMatrix;
varying vec4 v_Color;
void main() {
gl_Position = u_mvpMatrix * a_Position;
v_Color = a_Color;
}
`
const FSHADER_SOURCE = `
precision mediump float;
varying vec4 v_Color;
void main() {
gl_FragColor = v_Color;
}
`
const program = createProgram(gl, VSHADER_SOURCE, FSHADER_SOURCE)
gl.useProgram(program)
gl.clearColor(0, 0, 0, 1)
const verticesColors = new Float32Array([
0.0, 2.5, -5.0, 0.0, 1.0, 0.0,
-2.5, -2.5, -5.0, 0.0, 1.0, 0.0,
2.5, -2.5, -5.0, 1.0, 0.0, 0.0,
0.0, 3.0, -5.0, 1.0, 0.0, 0.0,
-3.0, -3.0, -5.0, 1.0, 1.0, 0.0,
3.0, -3.0, -5.0, 1.0, 1.0, 0.0
])
const vertexColorBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer)
gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW)
const a_Position = gl.getAttribLocation(program, 'a_Position')
gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 24, 0)
gl.enableVertexAttribArray(a_Position)
const a_Color = gl.getAttribLocation(program, 'a_Color')
gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, 24, 12)
gl.enableVertexAttribArray(a_Color)
const u_mvpMatrix = gl.getUniformLocation(program, 'u_mvpMatrix')
const mvpMatrix = new Matrix4()
mvpMatrix.setPerspective(40, 1, 1, 100).lookAt(0, 0, 10, 0, 0, -100, 0, 1, 0)
gl.uniformMatrix4fv(u_mvpMatrix, false, mvpMatrix.elements)
gl.enable(gl.DEPTH_TEST)
gl.enable(gl.POLYGON_OFFSET_FILL)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.drawArrays(gl.TRIANGLES, 0, 3)
gl.polygonOffset(1.0, 1.0)
gl.drawArrays(gl.TRIANGLES, 3, 3)
function loadShader(gl, source, type) {
const shader = gl.createShader(type)
gl.shaderSource(shader, source)
gl.compileShader(shader)
const error = gl.getShaderInfoLog(shader)
if (error) throw new Error(error)
return shader
}
function createProgram(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
const vshader = loadShader(gl, VSHADER_SOURCE, gl.VERTEX_SHADER)
const fshader = loadShader(gl, FSHADER_SOURCE, gl.FRAGMENT_SHADER)
const program = gl.createProgram()
gl.attachShader(program, vshader)
gl.attachShader(program, fshader)
gl.linkProgram(program)
const error = gl.getProgramInfoLog(program)
if (error) throw new Error(error)
return program
}
</script>
</body>
</html>