GLSLEffect.cs 11.8 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
		public struct ActiveEffect : IDisposable {
pcy's avatar
lol    
pcy committed
60
			internal GraphicsDevice gd;
61
			internal uint oldprgm;
pcy's avatar
pcy committed
62
			internal List<TexT> texs;
63
64
			bool disposed;

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

pcy's avatar
lol    
pcy committed
69
			public unsafe void Dispose() {
70
71
				if (disposed) return;

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

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

pcy's avatar
pcy committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
				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
96

pcy's avatar
lol    
pcy committed
97
98
99
100
				GL.DebugMessageControl(GL.DONT_CARE, GL.DEBUG_TYPE_ERROR,
						GL.DONT_CARE, 0, null, 1);
				GL.GetError();

101
102
103
104
				disposed = true;
			}
		}

pcy's avatar
pcy committed
105
106
		static int maxTextureSlots = -1;

pcy's avatar
lol    
pcy committed
107
108
		GraphicsDevice gd;

pcy's avatar
initial  
pcy committed
109
110
111
		uint[] glshdrs;
		uint glprgm;

112
113
		EffectTechnique fakeTech;

114
115
116
		IntPtr unifDataBacking;
		UnifData[] unifs;

pcy's avatar
pcy committed
117
		//readonly static List<EffectTechnique> emptyEffTechList = new List<EffectTechnique>();
pcy's avatar
initial  
pcy committed
118
119
120
		public unsafe GLSLEffect(GraphicsDevice gd,
					IDictionary<GLSLPurpose, string> shaders)
				: base(/*UGLY hack*/new BasicEffect(gd)) {
pcy's avatar
lol    
pcy committed
121
			this.gd = gd;
122
			fakeTech = Techniques[0];
123
			unifDataBacking = IntPtr.Zero;
124
125
126
127

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

pcy's avatar
initial  
pcy committed
128
			GL.Init(gd);
pcy's avatar
pcy committed
129
			GL.GetError(); // ignore errors from FNA/mojoshader
pcy's avatar
initial  
pcy committed
130

pcy's avatar
pcy committed
131
132
133
134
135
			if (maxTextureSlots < 0) {
				maxTextureSlots = GL.GetIntegerv(GL.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
				GL.Throw();
			}

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

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

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

pcy's avatar
pcy committed
187
188
189
190
191
				glshdrs = shdrs;
				glprgm  = prgm ;

				ParseAttribUnif();

pcy's avatar
initial  
pcy committed
192
193
194
195
196
197
198
199
200
201
202
203
				ok = true;
			}
			finally {
				if (!ok) {
					DelShdrPrgm();
				} else {
					glshdrs = shdrs;
					glprgm  = prgm ;
				}
			}
		}

pcy's avatar
pcy committed
204
		/*readonly static EffectParameterCollection  emptyParamColl
205
206
			= ReflUtil.CreateParamColl(new List<EffectParameter >());
		readonly static EffectAnnotationCollection emptyAnnotColl
pcy's avatar
pcy committed
207
			= ReflUtil.CreateAnnotColl(new List<EffectAnnotation>());*/
pcy's avatar
pcy committed
208
		void ParseAttribUnif() {
209
			/*int attrs = GL.GetProgramiv(glprgm, GL.ACTIVE_ATTRIBUTES);
pcy's avatar
pcy committed
210
211
212
213
214
215
216
217
218
219
220
221
			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+"}");
222
			}*/
pcy's avatar
pcy committed
223

224
			int nunifs = GL.GetProgramiv(glprgm, GL.ACTIVE_UNIFORMS);
pcy's avatar
pcy committed
225
			GL.Throw();
226
227
228
229
230
			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
231
232
233
234
235
236
237
				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();

238
239
240
241
242
243
244
				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
245
			ILUtil.Initblk(bleh, 0, (IntPtr)totalsize);
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
			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
270
			}
271
		}
pcy's avatar
pcy committed
272

pcy's avatar
pcy committed
273
		List<TexT> usedTextures = new List<TexT>();
274
		void ApplyUnifs() {
pcy's avatar
pcy committed
275
276
277
			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
278

pcy's avatar
pcy committed
279
280
281
282
283
284
285
286
			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
287

pcy's avatar
pcy committed
288
289
290
					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
291

pcy's avatar
pcy committed
292
293
294
295
296
					data = (IntPtr)((long)data + u.bytesize);
				}
			} finally {
				GL.ActiveTexture(actSlot);
			}
pcy's avatar
pcy committed
297
298
		}

299
300
301
302
		// 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
lol    
pcy committed
303
		public unsafe ActiveEffect Bind() { // TODO: how to warn on discarding the retval?
pcy's avatar
pcy committed
304
305
			GL.GetError(); // ignore errors from FNA/mojoshader

306
307
308
309
			// workaround FNA crap
			CurrentTechnique = fakeTech;
			fakeTech.Passes[0].Apply();

310
311
312
313
314
315
			uint oldprgm = unchecked((uint)GL.GetIntegerv(GL.CURRENT_PROGRAM));
			GL.Throw();

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

316
			ApplyUnifs();
317

pcy's avatar
lol    
pcy committed
318
319
320
321
322
323
324
325
326
327
328
			/*
			 * FNA will fail binding vertex attributes because it sets the
			 * vertex array buffer to 0 while passing non-null ptrs to
			 * glVertexAttribArray, which is an INVALID_OPERATION. When FNA is
			 * compiled with debugging enabled, this will throw an exception.
			 * (libmojoshader will also call a glUniform which will also most
			 *  likely fail)
			 *
			 * so what we do is we disable DEBUG_TYPE_ERRORs and set up vertex
			 * attributes ourselves (and undo that afterwards)
			 */
pcy's avatar
pcy committed
329
330
			//// TODO: we kinda need the vertex format in the first place...
			// eh, seems to work without...
pcy's avatar
lol    
pcy committed
331
332
333
334
335
336

			GL.DebugMessageControl(GL.DONT_CARE, GL.DEBUG_TYPE_ERROR,
					GL.DONT_CARE, 0, null, 0);
			GL.GetError();

			return new ActiveEffect(gd, oldprgm, usedTextures);
337
338
339
340
		}
		[Obsolete("Please use Bind() instead")]
		public ActiveEffect Apply() { return Bind(); }

pcy's avatar
initial  
pcy committed
341
		void DelShdrPrgm() {
pcy's avatar
pcy committed
342
			for (int i = 0; glshdrs != null && i < glshdrs.Length; ++i)
343
344
				if (glshdrs[i] != 0)
					GL.DeleteShader(glshdrs[i]);
pcy's avatar
pcy committed
345
			glshdrs = null;
pcy's avatar
initial  
pcy committed
346

347
348
			if (glprgm != 0)
				GL.DeleteProgram(glprgm);
pcy's avatar
initial  
pcy committed
349
350
351
352
353
		}

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

355
356
357
358
359
360
361
362
363
				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
364
365
366
367
			}

			base.Dispose(disposing);
		}
pcy's avatar
pcy committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411

		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
412
413
414
	}
}