GLSLEffect.cs 10.9 KB
Newer Older
pcy's avatar
initial  
pcy committed
1
2
3
using System;
using System.Collections.Generic;
using System.Linq;
4
using System.Runtime.InteropServices;
pcy's avatar
initial  
pcy committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
19
20
21
 *       -> set up uniforms and vertex arrays!
 *       --> circumvent? --> HOW??
 *       --> just go with it?? --> glProgramReady ok, glProgramViewportInfo might segfault!
22
 *
pcy's avatar
initial  
pcy committed
23
 * * samplers, textures
24
25
 *   -> https://www.khronos.org/opengl/wiki/Program_Introspection
 *   -> https://stackoverflow.com/questions/440144/in-opengl-is-there-a-way-to-get-a-list-of-all-uniforms-attribs-used-by-a-shade#442819
pcy's avatar
pcy committed
26
27
28
29
 *   -> https://www.khronos.org/opengl/wiki/Basic_Type_(GLSL)
 *
 *   -> https://www.khronos.org/opengl/wiki/Sampler_(GLSL)
 *   -> https://www.khronos.org/opengl/wiki/Texture
30
 * * vertex format verification!
pcy's avatar
initial  
pcy committed
31
32
33
 */

namespace PoroCYon.FNAGLSL {
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
	struct UnifData {
		public int location;
		public string name;
		public GLSLType type;
		public int size;
		public int rows, cols;
		public EffectParameterClass epclass;
		public EffectParameterType eptype;
		public uint bytesize;

		public UnifData(int loc, string n, GLSLType t, int sz, int r, int c,
				EffectParameterClass epc, EffectParameterType ept, uint bsz) {
			location = loc; name = n; type = t; size = sz; rows = r;
			cols = c; epclass = epc; eptype = ept; bytesize = bsz;
		}
	}
pcy's avatar
pcy committed
50
51
52
53
54
55
56
	struct TexT {
		public uint slot, getn, setn, texid;

		public TexT(uint sl, uint g, uint s, uint t) {
			slot = sl; getn = g; setn = s; texid = t;
		}
	};
57
58

	public partial class GLSLEffect : Effect {
59
60
		public struct ActiveEffect : IDisposable {
			internal uint oldprgm;
pcy's avatar
pcy committed
61
			internal List<TexT> texs;
62
63
			bool disposed;

pcy's avatar
pcy committed
64
			internal ActiveEffect(uint old, List<TexT> ts) {
pcy's avatar
pcy committed
65
				oldprgm = old; disposed = false; texs = ts;
66
67
68
69
70
			}

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

pcy's avatar
pcy committed
71
72
				GL.GetError();

73
				GL.UseProgram(oldprgm);
pcy's avatar
pcy committed
74
				GL.Throw();
75
76
				oldprgm = 0;

pcy's avatar
pcy committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
				uint actSlot = unchecked((uint)GL.GetIntegerv(GL.ACTIVE_TEXTURE));
				GL.Throw();
				try {
					for (int i = 0; i < texs.Count; ++i) {
						GL.ActiveTexture(GL.TEXTURE0 + texs[i].slot);
						GL.Throw();
						GL.BindTexture(texs[i].setn, 0);
						GL.Throw();

						/*Console.WriteLine("clear slot " + texs[i].slot + " texid " + texs[i].texid
							+ " getn 0x" + texs[i].getn.ToString("X") + " setn 0x" + texs[i].setn.ToString("X"));*/

					}
				} finally {
					GL.ActiveTexture(actSlot);
					//GL.Throw();
					texs.Clear();
				}
pcy's avatar
pcy committed
95

96
97
98
99
				disposed = true;
			}
		}

pcy's avatar
pcy committed
100
101
		static int maxTextureSlots = -1;

pcy's avatar
initial  
pcy committed
102
103
104
		uint[] glshdrs;
		uint glprgm;

105
106
		EffectTechnique fakeTech;

107
108
109
		IntPtr unifDataBacking;
		UnifData[] unifs;

pcy's avatar
pcy committed
110
		//readonly static List<EffectTechnique> emptyEffTechList = new List<EffectTechnique>();
pcy's avatar
initial  
pcy committed
111
112
113
		public unsafe GLSLEffect(GraphicsDevice gd,
					IDictionary<GLSLPurpose, string> shaders)
				: base(/*UGLY hack*/new BasicEffect(gd)) {
114
			fakeTech = Techniques[0];
115
			unifDataBacking = IntPtr.Zero;
116
117
118
119

			// cause NullRefExns when dumb code would try to access the techns
			this.SetTechniques(null/*ReflUtil.CreateTechColl(emptyEffTechList)*/);

pcy's avatar
initial  
pcy committed
120
			GL.Init(gd);
pcy's avatar
pcy committed
121
			GL.GetError(); // ignore errors from FNA/mojoshader
pcy's avatar
initial  
pcy committed
122

pcy's avatar
pcy committed
123
124
125
			GL.Enable(GL.DEBUG_OUTPUT_SYNCHRONOUS);
			GL.Throw();

pcy's avatar
pcy committed
126
127
128
129
130
			if (maxTextureSlots < 0) {
				maxTextureSlots = GL.GetIntegerv(GL.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
				GL.Throw();
			}

131
132
133
134
			// 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);
135
136
			this.SetGLEffectData(IntPtr.Zero);
			this.SetEffectData  (IntPtr.Zero);*/
137
138
139
140
141
142
			// 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156

			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();

pcy's avatar
pcy committed
157
					GL.ShaderSource(sh, kvp.Value);
pcy's avatar
initial  
pcy committed
158
159
160
161
162
163
					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);
pcy's avatar
pcy committed
164
165
166
						var msg = GL.GetShaderInfoLog(sh, len);
						throw new GLSLCompileException("Failed to compile "
								+ kvp.Key + ": " + msg);
pcy's avatar
initial  
pcy committed
167
168
169
170
171
172
173
174
175
176
177
					}

					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);
pcy's avatar
pcy committed
178
179
					var msg = GL.GetProgramInfoLog(prgm, len);
					throw new GLSLLinkException("Failed to link shader: " + msg);
pcy's avatar
initial  
pcy committed
180
181
				}

pcy's avatar
pcy committed
182
183
184
185
186
				glshdrs = shdrs;
				glprgm  = prgm ;

				ParseAttribUnif();

pcy's avatar
initial  
pcy committed
187
188
189
190
191
192
193
194
195
196
197
198
				ok = true;
			}
			finally {
				if (!ok) {
					DelShdrPrgm();
				} else {
					glshdrs = shdrs;
					glprgm  = prgm ;
				}
			}
		}

pcy's avatar
pcy committed
199
		/*readonly static EffectParameterCollection  emptyParamColl
200
201
			= ReflUtil.CreateParamColl(new List<EffectParameter >());
		readonly static EffectAnnotationCollection emptyAnnotColl
pcy's avatar
pcy committed
202
			= ReflUtil.CreateAnnotColl(new List<EffectAnnotation>());*/
pcy's avatar
pcy committed
203
		void ParseAttribUnif() {
204
			/*int attrs = GL.GetProgramiv(glprgm, GL.ACTIVE_ATTRIBUTES);
pcy's avatar
pcy committed
205
206
207
208
209
210
211
212
213
214
215
216
			GL.Throw();
			Console.WriteLine("#attrs = " + attrs);
			for (int i = 0; i < attrs; ++i) {
				int size; GLSLType type; string name;
				GL.GetActiveAttrib(glprgm, unchecked((uint)i), out size,
						out type, out name);
				GL.Throw();
				int loc = GL.GetAttribLocation(glprgm, name);
				GL.Throw();

				Console.WriteLine("attrs["+i+"] = {size=" + size + ", type="
						+ type + ", name=" + name + ", loc="+loc+"}");
217
			}*/
pcy's avatar
pcy committed
218

219
			int nunifs = GL.GetProgramiv(glprgm, GL.ACTIVE_UNIFORMS);
pcy's avatar
pcy committed
220
			GL.Throw();
221
222
223
224
225
			unifs = new UnifData[nunifs];
			var parms = new List<EffectParameter>();
			uint totalsize = 0;
			//Console.WriteLine("#unifs = " + nunifs);
			for (int i = 0; i < nunifs; ++i) {
pcy's avatar
pcy committed
226
227
228
229
230
231
232
				int size; GLSLType type; string name;
				GL.GetActiveUniform(glprgm, unchecked((uint)i), out size,
						out type, out name);
				GL.Throw();
				int loc = GL.GetUniformLocation(glprgm, name);
				GL.Throw();

233
234
235
236
237
238
239
				uint bytesize = unchecked((uint)(typ2size[type]*size));
				unifs[i] = new UnifData(loc, name, type, size, GetRows(type),
					GetCols(type), typ2class[type], typ2type[type], bytesize);
				totalsize += bytesize;
			}

			IntPtr bleh = Marshal.AllocHGlobal((IntPtr)totalsize);
pcy's avatar
pcy committed
240
			ILUtil.Initblk(bleh, 0, (IntPtr)totalsize);
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
			bool ok = false;

			try {
				uint sizepos = 0;
				for (int i = 0; i < nunifs; ++i) {
					var u = unifs[i];

					IntPtr bps = (IntPtr)((long)bleh + sizepos);
					parms.Add(ReflUtil.CreateParameter(u.name, null/*semantic: ???*/,
							u.rows, u.cols, (u.size == 1) ? 0 : u.size,
							u.epclass, u.eptype, null, null, //emptyParamColl, emptyAnnotColl,
							bps, u.bytesize));
					sizepos += u.bytesize;
				}

				ok = true;
			} finally {
				if (ok) {
					unifDataBacking = bleh;
					this.SetParameters(ReflUtil.CreateParamColl(parms));
				} else {
					Marshal.FreeHGlobal(bleh);
					unifDataBacking = IntPtr.Zero;
				}
pcy's avatar
pcy committed
265
			}
266
		}
pcy's avatar
pcy committed
267

pcy's avatar
pcy committed
268
		List<TexT> usedTextures = new List<TexT>();
269
		void ApplyUnifs() {
pcy's avatar
pcy committed
270
271
272
			usedTextures.Clear();
			// TODO: get active texture to restore later -> glGetIntegerv(GL_ACTIVE_TEXTURE)
			// TODO: make list to hold used texture slots
pcy's avatar
pcy committed
273

pcy's avatar
pcy committed
274
275
276
277
278
279
280
281
			uint actSlot = unchecked((uint)GL.GetIntegerv(GL.ACTIVE_TEXTURE));
			GL.Throw();
			try {
				IntPtr data = unifDataBacking;
				uint firstEmptySlot = 0;
				for (int i = 0; i < unifs.Length; ++i) {
					var u = unifs[i];
					var p = Parameters[i];
pcy's avatar
pcy committed
282

pcy's avatar
pcy committed
283
284
285
					if (Array.IndexOf(GL.samplerTypes, (uint)u.type) >= 0) // it's a texture
						SetTexture(ref firstEmptySlot, ref u, p);
					else SetUniform(ref u, data);
pcy's avatar
pcy committed
286

pcy's avatar
pcy committed
287
288
289
290
291
					data = (IntPtr)((long)data + u.bytesize);
				}
			} finally {
				GL.ActiveTexture(actSlot);
			}
pcy's avatar
pcy committed
292
293
		}

294
295
296
297
		// 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
298
299
300
		public ActiveEffect Bind() { // TODO: how to warn on discarding the retval?
			GL.GetError(); // ignore errors from FNA/mojoshader

301
302
303
304
			// workaround FNA crap
			CurrentTechnique = fakeTech;
			fakeTech.Passes[0].Apply();

305
306
307
308
309
310
			uint oldprgm = unchecked((uint)GL.GetIntegerv(GL.CURRENT_PROGRAM));
			GL.Throw();

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

311
			ApplyUnifs();
312

pcy's avatar
pcy committed
313
			return new ActiveEffect(oldprgm, usedTextures);
314
315
316
317
		}
		[Obsolete("Please use Bind() instead")]
		public ActiveEffect Apply() { return Bind(); }

pcy's avatar
initial  
pcy committed
318
		void DelShdrPrgm() {
pcy's avatar
pcy committed
319
			for (int i = 0; glshdrs != null && i < glshdrs.Length; ++i)
320
321
				if (glshdrs[i] != 0)
					GL.DeleteShader(glshdrs[i]);
pcy's avatar
pcy committed
322
			glshdrs = null;
pcy's avatar
initial  
pcy committed
323

324
325
			if (glprgm != 0)
				GL.DeleteProgram(glprgm);
pcy's avatar
initial  
pcy committed
326
327
328
329
330
		}

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

332
333
334
335
336
337
338
339
340
				if (fakeTech != null) {
					this.SetTechniques(ReflUtil.CreateTechColl(new[]{fakeTech}.ToList()));
					fakeTech = null;
				}

				if (unifDataBacking != IntPtr.Zero) {
					Marshal.FreeHGlobal(unifDataBacking);
					unifDataBacking = IntPtr.Zero;
				}
pcy's avatar
initial  
pcy committed
341
342
343
344
			}

			base.Dispose(disposing);
		}
pcy's avatar
pcy committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

		unsafe void SetTexture(ref uint firstEmpty, ref UnifData u, EffectParameter p) {
			uint getn = typ2getn[u.type]/*,
			     setn = typ2setn[u.type]*/;

			// find a free texture slot
			bool foundSlot = false;
			for (uint j = firstEmpty; j < maxTextureSlots; ++j) {
				GL.ActiveTexture(GL.TEXTURE0 + j);
				GL.Throw();
				uint curbound = unchecked((uint)GL.GetIntegerv(getn));
				GL.Throw();

				if (curbound == 0) { // free!
					var tar = p.GetValueTexture();
					if (tar == null)
						throw new InvalidOperationException("texture of param '"
								+ u.name + "'is null?!");

					uint setn = unchecked((uint)tar.GetGLTexTarget());
					uint texn = tar.GetGLTexID();

					/*Console.WriteLine("set slot " + j + " texid " + texn
							+ " getn 0x" + getn.ToString("X") + " setn 0x" + setn.ToString("X")
							+ " -> to unif. " + u.name);*/

					// bind the uniform to the texture slot
					GL.Uniform1i(u.location, unchecked((int)j));
					GL.Throw();

					// bind the texture to the texture slot!
					GL.BindTexture(setn, texn);
					GL.Throw();
					usedTextures.Add(new TexT(j, getn, setn, texn));
					firstEmpty = j+1;
					foundSlot = true;
					break;
				}
			}

			if (!foundSlot)
				throw new InvalidOperationException("param '" + u.name
						+ "': can't find a free texture slot...");
		}
pcy's avatar
initial  
pcy committed
389
390
391
	}
}