-
Notifications
You must be signed in to change notification settings - Fork 5
/
ShaderProgram.cs
114 lines (86 loc) · 2.81 KB
/
ShaderProgram.cs
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
namespace glvertexid;
public unsafe class ShaderProgram
{
public static string VERSION = "#version 330\n";
public ShaderProgram(string vertexShaderSource, string fragmentShaderSource)
{
Initialise(vertexShaderSource, fragmentShaderSource);
}
void Initialise(string vertexShaderSource, string fragmentShaderSource)
{
try
{
vertexShader = new Shader(ShaderType.VertexShader, VERSION + vertexShaderSource);
fragmentShader = new Shader(ShaderType.FragmentShader, VERSION + fragmentShaderSource);
}
catch (Exception e)
{
Console.WriteLine(e);
Dispose();
throw;
}
// Create shader program.
programHandle = Gl.CreateProgram();
// Attach shaders to the program
Gl.AttachShader(programHandle, vertexShader.shaderHandle);
Gl.AttachShader(programHandle, fragmentShader.shaderHandle);
Gl.LinkProgram(programHandle);
// Get the log
Gl.GetProgram(programHandle, ProgramPropertyARB.InfoLogLength, out int logLen);
if (logLen > 0)
{
Gl.GetProgramInfoLog(programHandle, (uint)logLen, out _, out string log);
if (!string.IsNullOrEmpty(log))
Console.WriteLine($"Program link log:\n{log}");
}
// Clean up
Gl.DetachShader(programHandle, vertexShader.shaderHandle);
Gl.DetachShader(programHandle, fragmentShader.shaderHandle);
// Ensure the shaders were linked correctly
Gl.GetProgram(programHandle, ProgramPropertyARB.LinkStatus, out int status);
if (status == 0)
{
Console.WriteLine($"Shader link failed. Status: {status}");
AssertFalse();
}
Unbind();
}
public virtual void UseProgram()
{
// Already current, all good
if (Active)
return;
Gl.UseProgram(programHandle);
CurrentHandle = programHandle;
}
public static void Unbind()
{
Gl.UseProgram(0);
CurrentHandle = 0;
}
public int GetUniformLocation(string name) => Gl.GetUniformLocation(programHandle, name);
public void Dispose()
{
if (vertexShader != null)
{
vertexShader.Dispose();
vertexShader = null;
}
if (fragmentShader != null)
{
fragmentShader.Dispose();
fragmentShader = null;
}
if (programHandle != 0)
{
Gl.DeleteProgram(programHandle);
programHandle = 0;
}
}
// Remember which is the current shader program
static uint CurrentHandle;
public bool Active => CurrentHandle == programHandle;
Shader vertexShader;
Shader fragmentShader;
protected uint programHandle;
}