GLSLEffect.cs 4.42 KB
Newer Older
pcy's avatar
initial  
pcy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

/* TODO:
 * * apply
 *   * HOW????
 *   * OnApply: protecteed internal :(
 *   * INTERNAL_applyEffect: internal...
 *     + calls mojoshader! --> hijack?!!
 *       -> glEffect{Begin,End}: state mgmt | unbind shader!
 *       -> glEffect{Begin,End}Pass: bind shader! | state mgmt
 *   * GD draw calls: ok
 *     * EXCEPT mojoshader: glProgramReady, glProgramViewportInfo
18
19
20
 *       -> set up uniforms and vertex arrays!
 *       --> circumvent? --> HOW??
 *       --> just go with it?? --> glProgramReady ok, glProgramViewportInfo might segfault!
pcy's avatar
initial  
pcy committed
21
22
23
24
25
26
 * * uniforms
 * * samplers, textures
 */

namespace PoroCYon.FNAGLSL {
	public class GLSLEffect : Effect {
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
		public struct ActiveEffect : IDisposable {
			internal uint oldprgm;
			bool disposed;

			internal ActiveEffect(uint old) {
				oldprgm = old; disposed = false;
			}

			public void Dispose() {
				if (disposed) return;

				GL.UseProgram(oldprgm);
				oldprgm = 0;

				disposed = true;
			}
		}

pcy's avatar
initial  
pcy committed
45
46
47
48
49
50
51
		uint[] glshdrs;
		uint glprgm;

		public unsafe GLSLEffect(GraphicsDevice gd,
					IDictionary<GLSLPurpose, string> shaders)
				: base(/*UGLY hack*/new BasicEffect(gd)) {
			GL.Init(gd);
pcy's avatar
pcy committed
52
			GL.GetError(); // ignore errors from FNA/mojoshader
pcy's avatar
initial  
pcy committed
53

54
55
56
57
58
59
60
61
62
63
64
65
			// this basically makes FNA think this effect is a noop, so binding
			// this effect will do the same as binding the 0 program in OpenGL,
			// so the BasicEffect used won't do much anymore
			/*gd.DeleteEffect(this);
			eff.SetGLEffectData(IntPtr.Zero);
			eff.SetEffectData  (IntPtr.Zero);*/
			// turns out we can't do this, or libmojoshader will segfault
			// because it lacks some null checking in
			// glEffectEnd, glEffectBeginPass, glProgramViewportInfo :/ ...
			// so we basically have to make sure the usual route of Apply()ing
			// the shader happens (unless we can circumvent this *somehow*),
			// and then apply the shader manually.
pcy's avatar
initial  
pcy committed
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128

			var shdrs = new uint[shaders.Count];
			bool ok = false;
			uint prgm = 0;

			try {
				prgm = GL.CreateProgram();
				if (prgm == 0) GL.Throw();

				int i = 0;
				foreach (var kvp in shaders) {
					uint sh = GL.CreateShader(kvp.Key);
					if (sh == 0) GL.Throw();

					byte[] utf8src = Encoding.UTF8.GetBytes(kvp.Value);
					fixed (byte* sbuf = utf8src) {
						sbyte** uurgh = stackalloc sbyte*[1];
						*uurgh = (sbyte*)sbuf;
						int* uurgh2 = stackalloc int[1];
						*uurgh2 = utf8src.Length;
						GL.ShaderSource(sh, 1, uurgh, uurgh2);
					}
					GL.Throw();

					GL.CompileShader(sh);

					if (GL.GetError() != 0 || GL.GetShaderiv(sh, GL.COMPILE_STATUS) == 0) {
						int len = GL.GetShaderiv(sh, GL.INFO_LOG_LENGTH);
						var msg = new sbyte[len];
						fixed (sbyte* buf = msg) {
							GL.GetShaderInfoLog(sh, len, null, buf);
							throw new GLSLCompileException(new String(buf, 0, len-1));
						}
					}

					GL.AttachShader(prgm, sh);
					GL.Throw();

					shdrs[i++] = sh;
				}

				GL.LinkProgram(prgm);
				if (GL.GetError() != 0 || GL.GetProgramiv(prgm, GL.LINK_STATUS) == 0) {
					int len = GL.GetProgramiv(prgm, GL.INFO_LOG_LENGTH);
					var msg = new sbyte[len];
					fixed (sbyte* buf = msg) {
						GL.GetProgramInfoLog(prgm, len, null, buf);
						throw new GLSLLinkException(new String(buf, 0, len-1));
					}
				}

				ok = true;
			}
			finally {
				if (!ok) {
					DelShdrPrgm();
				} else {
					glshdrs = shdrs;
					glprgm  = prgm ;
				}
			}
		}

129
130
131
132
		// TODO: find out a better (i.e. more API-conform) way to do this!
		///<summary>
		///USAGE: using (var eff &eq; glslEffect.Bind()) { ... gd.DrawPrimitives(...); ... }
		///</summary>
pcy's avatar
pcy committed
133
134
135
		public ActiveEffect Bind() { // TODO: how to warn on discarding the retval?
			GL.GetError(); // ignore errors from FNA/mojoshader

136
137
138
139
140
141
142
143
144
145
146
147
148
			uint oldprgm = unchecked((uint)GL.GetIntegerv(GL.CURRENT_PROGRAM));
			GL.Throw();

			GL.UseProgram(glprgm);
			GL.Throw();

			// TODO: apply uniforms and samplers! (XNA API -> OpenGL state)

			return new ActiveEffect(oldprgm);
		}
		[Obsolete("Please use Bind() instead")]
		public ActiveEffect Apply() { return Bind(); }

pcy's avatar
initial  
pcy committed
149
		void DelShdrPrgm() {
pcy's avatar
pcy committed
150
			for (int i = 0; glshdrs != null && i < glshdrs.Length; ++i)
151
152
				if (glshdrs[i] != 0)
					GL.DeleteShader(glshdrs[i]);
pcy's avatar
pcy committed
153
			glshdrs = null;
pcy's avatar
initial  
pcy committed
154

155
156
			if (glprgm != 0)
				GL.DeleteProgram(glprgm);
pcy's avatar
initial  
pcy committed
157
158
159
160
161
162
163
164
165
166
167
168
		}

		protected override void Dispose(bool disposing) {
			if (!IsDisposed) {
				DelShdrPrgm();
			}

			base.Dispose(disposing);
		}
	}
}