Survivalcraft API 1.8.2.3 v1.8.2.3
Survivalcraft 2.4
载入中...
搜索中...
未找到
GLWrapper.cs
浏览该文件的文档.
1using Silk.NET.OpenGLES;
2using System.Diagnostics;
3#if BROWSER
5#endif
6#if DEBUG && !IOS
7using System.Runtime.InteropServices;
8#endif
9
10namespace Engine.Graphics {
11 public static class GLWrapper {
12 public static GL GL;
13#if ANGLE || BROWSER
14 public static IntPtr m_eglDisplay;
15 public static IntPtr m_eglSurface;
16 public static IntPtr m_eglContext;
17#endif
18
19 public static int m_mainFramebuffer;
20
21 public static int m_mainDepthbuffer;
22
23 public static int m_mainColorbuffer;
24 public static int m_arrayBuffer;
25 public static int m_elementArrayBuffer;
26 public static int m_texture2D;
27 public static int[] m_activeTexturesByUnit;
28 public static TextureUnit m_activeTextureUnit;
29 public static int m_program;
30 public static int m_framebuffer;
31 public static Vector4? m_clearColor;
32 public static float? m_clearDepth;
33 public static int? m_clearStencil;
34 public static TriangleFace m_cullFace;
35 public static FrontFaceDirection m_frontFace;
36 public static DepthFunction m_depthFunction;
37 public static int? m_colorMask;
38 public static bool? m_depthMask;
39 public static float m_polygonOffsetFactor;
40 public static float m_polygonOffsetUnits;
41 public static Vector4 m_blendColor;
42 public static BlendEquationModeEXT m_blendEquation;
43 public static BlendEquationModeEXT m_blendEquationColor;
44 public static BlendEquationModeEXT m_blendEquationAlpha;
45 public static BlendingFactor m_blendFuncSource;
46 public static BlendingFactor m_blendFuncSourceColor;
47 public static BlendingFactor m_blendFuncSourceAlpha;
48 public static BlendingFactor m_blendFuncDestination;
49 public static BlendingFactor m_blendFuncDestinationColor;
50 public static BlendingFactor m_blendFuncDestinationAlpha;
51 public static Dictionary<EnableCap, bool> m_enableDisableStates;
52 public static bool?[] m_vertexAttribArray;
55 public static BlendState m_blendState;
56 public static Dictionary<int, SamplerState> m_textureSamplerStates;
57 public static Shader m_lastShader;
59 public static IntPtr m_lastVertexOffset;
60 public static int m_lastArrayBuffer;
61 public static Viewport? m_viewport;
63
65 public static bool GL_OES_packed_depth_stencil;
68 public static int GL_MAX_TEXTURE_SIZE;
69
70 public static void Initialize() {
71#if ANGLE || BROWSER
72#if ANGLE
73 IntPtr hwnd = Window.Handle;
74 if (hwnd == IntPtr.Zero) {
75 throw new Exception("Failed to get window handle");
76 }
77#endif
78 m_eglDisplay = Egl.GetDisplay(IntPtr.Zero);
79 if (m_eglDisplay == IntPtr.Zero) {
80 throw new Exception("eglGetDisplay failed");
81 }
82 if (!Egl.Initialize(m_eglDisplay, out _, out _)) {
83 throw new Exception("eglInitialize failed");
84 }
85 int[] configAttribs = [
87 8,
89 8,
91 8,
93 8,
95 24,
97 8,
103 ];
104 IntPtr[] configs = new IntPtr[1];
105 if (!Egl.ChooseConfig(m_eglDisplay, configAttribs, configs, 1, out int numConfigs)) {
106 throw new Exception("eglChooseConfig failed");
107 }
108 IntPtr config = configs[0];
109#if ANGLE
110 m_eglSurface = Egl.CreateWindowSurface(m_eglDisplay, config, hwnd, [Egl.None]);
111#else
112 m_eglSurface = Egl.CreateWindowSurface(m_eglDisplay, config, IntPtr.Zero, [Egl.None]);
113#endif
114 if (m_eglSurface == IntPtr.Zero) {
115 throw new Exception("eglCreateWindowSurface failed");
116 }
117 int[] contextAttribs = [Egl.ContextClientVersion, 3, Egl.None];
118 m_eglContext = Egl.CreateContext(m_eglDisplay, config, IntPtr.Zero, contextAttribs);
119 if (m_eglContext == IntPtr.Zero) {
120 throw new Exception("eglCreateContext failed");
121 }
122 if (!Egl.MakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext)) {
123 throw new Exception("eglMakeCurrent failed");
124 }
125#if BROWSER
127#endif
128 GL = GL.GetApi(Egl.GetProcAddress);
129#else
130 GL = GL.GetApi(Window.m_view);
131#endif
132#if IOS
133 m_mainFramebuffer = GL.GetInteger((GLEnum)GetPName.DrawFramebufferBinding);
134 m_mainDepthbuffer = GL.GetInteger((GLEnum)GetPName.RenderbufferBinding);
135 m_mainColorbuffer = GL.GetInteger(GLEnum.ColorAttachment0);
136#else
138#endif
139#if DEBUG && !IOS && !BROWSER
140 unsafe {
141 GL.DebugMessageCallback(DebugMessageDelegate, IntPtr.Zero.ToPointer());
142 GL.Enable(EnableCap.DebugOutput);
143 }
144#endif
145 int[] bits = new int[6];
146 for (int i = 0; i < 6; i++) {
147 bits[i] = GL.GetInteger((GetPName)(i + 3410));
148 }
149 GL.GetInteger(GetPName.MaxTextureSize, out GL_MAX_TEXTURE_SIZE);
150 string OpenGLVendor = $"OpenGL ES, Vendor={GL.GetStringS(StringName.Vendor) ?? string.Empty}";
151 Display.DeviceDescription =
152 $"{OpenGLVendor}, Renderer={GL.GetStringS(StringName.Renderer) ?? string.Empty}, Version={GL.GetStringS(StringName.Version) ?? string.Empty}, R={bits[0]} G={bits[1]} B={bits[2]} A={bits[3]}, D={bits[4]} S={bits[5]}, MaxTextureSize={GL_MAX_TEXTURE_SIZE}";
153 Log.Information($"Initialized display device: {Display.DeviceDescription}");
154 string extensions = GL.GetStringS(StringName.Extensions);
155 GL_EXT_texture_filter_anisotropic = extensions?.Contains("GL_EXT_texture_filter_anisotropic") ?? false;
156 GL_OES_packed_depth_stencil = extensions?.Contains("GL_OES_packed_depth_stencil") ?? false;
157 GL_KHR_texture_compression_astc_ldr = extensions?.Contains("GL_KHR_texture_compression_astc_ldr") ?? false;
158 GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = GL.GetInteger(GetPName.MaxCombinedTextureImageUnits);
159 }
160
161 public static void InitializeCache() {
162 m_arrayBuffer = -1;
164 m_texture2D = -1;
166 -1,
167 -1,
168 -1,
169 -1,
170 -1,
171 -1,
172 -1,
173 -1
174 ];
175 m_activeTextureUnit = (TextureUnit)(-1);
176 m_program = -1;
177 m_framebuffer = -1;
178 m_clearColor = null;
179 m_clearDepth = null;
180 m_clearStencil = null;
181 m_cullFace = 0;
182 m_frontFace = 0;
183 m_depthFunction = (DepthFunction)(-1);
184 m_colorMask = null;
185 m_depthMask = null;
188 m_blendColor = new Vector4(float.MinValue);
189 m_blendEquation = (BlendEquationModeEXT)(-1);
190 m_blendEquationColor = (BlendEquationModeEXT)(-1);
191 m_blendEquationAlpha = (BlendEquationModeEXT)(-1);
192 m_blendFuncSource = (BlendingFactor)(-1);
193 m_blendFuncSourceColor = (BlendingFactor)(-1);
194 m_blendFuncSourceAlpha = (BlendingFactor)(-1);
195 m_blendFuncDestination = (BlendingFactor)(-1);
196 m_blendFuncDestinationColor = (BlendingFactor)(-1);
197 m_blendFuncDestinationAlpha = (BlendingFactor)(-1);
199 m_vertexAttribArray = new bool?[16];
200 m_rasterizerState = null;
201 m_depthStencilState = null;
202 m_blendState = null;
204 m_lastShader = null;
206 m_lastVertexOffset = IntPtr.Zero;
208 m_viewport = null;
209 m_scissorRectangle = null;
210 }
211
212 public static bool Enable(EnableCap state) {
213 if (!m_enableDisableStates.TryGetValue(state, out bool value)
214 || !value) {
215 GL.Enable(state);
216 m_enableDisableStates[state] = true;
217 return true;
218 }
219 return false;
220 }
221
222 public static bool Disable(EnableCap state) {
223 if (!m_enableDisableStates.TryGetValue(state, out bool value) | value) {
224 GL.Disable(state);
225 m_enableDisableStates[state] = false;
226 return true;
227 }
228 return false;
229 }
230
231 public static bool IsEnabled(EnableCap state) {
232 if (!m_enableDisableStates.TryGetValue(state, out bool value)) {
233 value = GL.IsEnabled(state);
234 m_enableDisableStates[state] = value;
235 }
236 return value;
237 }
238
239 public static void ClearColor(Vector4 color) {
240 Vector4 value = color;
241 Vector4? clearColor = m_clearColor;
242 if (value != clearColor) {
243 GL.ClearColor(color.X, color.Y, color.Z, color.W);
244 m_clearColor = color;
245 }
246 }
247
248 public static void ClearDepth(float depth) {
249 if (depth != m_clearDepth) {
250 GL.ClearDepth(depth);
251 m_clearDepth = depth;
252 }
253 }
254
255 public static void ClearStencil(int stencil) {
256 if (stencil != m_clearStencil) {
257 GL.ClearStencil(stencil);
258 m_clearStencil = stencil;
259 }
260 }
261
262 public static void CullFace(TriangleFace cullFace) {
263 if (cullFace != m_cullFace) {
264 GL.CullFace(cullFace);
265 m_cullFace = cullFace;
266 }
267 }
268
269 public static void FrontFace(FrontFaceDirection frontFace) {
270 if (frontFace != m_frontFace) {
271 GL.FrontFace(frontFace);
272 m_frontFace = frontFace;
273 }
274 }
275
276 public static void DepthFunc(DepthFunction depthFunction) {
277 if (depthFunction != m_depthFunction) {
278 GL.DepthFunc(depthFunction);
279 m_depthFunction = depthFunction;
280 }
281 }
282
283 public static void ColorMask(int colorMask) {
284 colorMask &= 0xF;
285 if (colorMask != m_colorMask) {
286 GL.ColorMask((colorMask & 8) != 0, (colorMask & 4) != 0, (colorMask & 2) != 0, (colorMask & 1) != 0);
287 m_colorMask = colorMask;
288 }
289 }
290
291 public static bool DepthMask(bool depthMask) {
292 if (depthMask != m_depthMask) {
293 GL.DepthMask(depthMask);
294 m_depthMask = depthMask;
295 return true;
296 }
297 return false;
298 }
299
300 public static void PolygonOffset(float factor, float units) {
301 if (factor != m_polygonOffsetFactor
302 || units != m_polygonOffsetUnits) {
303 GL.PolygonOffset(factor, units);
304 m_polygonOffsetFactor = factor;
305 m_polygonOffsetUnits = units;
306 }
307 }
308
309 public static void BlendColor(Vector4 blendColor) {
310 if (blendColor != m_blendColor) {
311 GL.BlendColor(blendColor.X, blendColor.Y, blendColor.Z, blendColor.W);
312 m_blendColor = blendColor;
313 }
314 }
315
316 public static void BlendEquation(BlendEquationModeEXT blendEquation) {
317 if (blendEquation != m_blendEquation) {
318 GL.BlendEquation(blendEquation);
319 m_blendEquation = blendEquation;
320 m_blendEquationColor = (BlendEquationModeEXT)(-1);
321 m_blendEquationAlpha = (BlendEquationModeEXT)(-1);
322 }
323 }
324
325 public static void BlendEquationSeparate(BlendEquationModeEXT blendEquationColor, BlendEquationModeEXT blendEquationAlpha) {
326 if (blendEquationColor != m_blendEquationColor
327 || blendEquationAlpha != m_blendEquationAlpha) {
328 GL.BlendEquationSeparate(blendEquationColor, blendEquationAlpha);
329 m_blendEquationColor = blendEquationColor;
330 m_blendEquationAlpha = blendEquationAlpha;
331 m_blendEquation = (BlendEquationModeEXT)(-1);
332 }
333 }
334
335 public static void BlendFunc(BlendingFactor blendFuncSource, BlendingFactor blendFuncDestination) {
336 if (blendFuncSource != m_blendFuncSource
337 || blendFuncDestination != m_blendFuncDestination) {
338 GL.BlendFunc(blendFuncSource, blendFuncDestination);
339 m_blendFuncSource = blendFuncSource;
340 m_blendFuncDestination = blendFuncDestination;
341 m_blendFuncSourceColor = (BlendingFactor)(-1);
342 m_blendFuncSourceAlpha = (BlendingFactor)(-1);
343 m_blendFuncDestinationColor = (BlendingFactor)(-1);
344 m_blendFuncDestinationAlpha = (BlendingFactor)(-1);
345 }
346 }
347
348 public static void BlendFuncSeparate(BlendingFactor blendFuncSourceColor,
349 BlendingFactor blendFuncDestinationColor,
350 BlendingFactor blendFuncSourceAlpha,
351 BlendingFactor blendFuncDestinationAlpha) {
352 if (blendFuncSourceColor != m_blendFuncSourceColor
353 || blendFuncDestinationColor != m_blendFuncDestinationColor
354 || blendFuncSourceAlpha != m_blendFuncSourceAlpha
355 || blendFuncDestinationAlpha != m_blendFuncDestinationAlpha) {
356 GL.BlendFuncSeparate(blendFuncSourceColor, blendFuncDestinationColor, blendFuncSourceAlpha, blendFuncDestinationAlpha);
357 m_blendFuncSourceColor = blendFuncSourceColor;
358 m_blendFuncSourceAlpha = blendFuncSourceAlpha;
359 m_blendFuncDestinationColor = blendFuncDestinationColor;
360 m_blendFuncDestinationAlpha = blendFuncDestinationAlpha;
361 m_blendFuncSource = (BlendingFactor)(-1);
362 m_blendFuncDestination = (BlendingFactor)(-1);
363 }
364 }
365
366 public static void VertexAttribArray(int index, bool enable) {
367 uint uIndex = (uint)index;
368 if (enable && (!m_vertexAttribArray[index].HasValue || !m_vertexAttribArray[index].Value)) {
369 GL.EnableVertexAttribArray(uIndex);
370 m_vertexAttribArray[index] = true;
371 }
372 else if (!enable
373 && (!m_vertexAttribArray[index].HasValue || m_vertexAttribArray[index].Value)) {
374 GL.DisableVertexAttribArray(uIndex);
375 m_vertexAttribArray[index] = false;
376 }
377 }
378
379 public static void BindTexture(TextureTarget target, int texture, bool forceBind) {
380 uint uTexture = (uint)texture;
381 if (target == TextureTarget.Texture2D) {
382 if (forceBind || texture != m_texture2D) {
383 GL.BindTexture(target, uTexture);
384 m_texture2D = texture;
385 if (m_activeTextureUnit >= 0) {
386 m_activeTexturesByUnit[(int)(m_activeTextureUnit - 33984)] = texture;
387 }
388 }
389 }
390 else {
391 GL.BindTexture(target, uTexture);
392 }
393 }
394
395 public static void ActiveTexture(TextureUnit textureUnit) {
396 if (textureUnit != m_activeTextureUnit) {
397 GL.ActiveTexture(textureUnit);
398 m_activeTextureUnit = textureUnit;
399 }
400 }
401
402 public static void BindBuffer(BufferTargetARB target, int buffer) {
403 uint uBuffer = (uint)buffer;
404 switch (target) {
405 case BufferTargetARB.ArrayBuffer:
406 if (buffer != m_arrayBuffer) {
407 GL.BindBuffer(target, uBuffer);
408 m_arrayBuffer = buffer;
409 }
410 break;
411 case BufferTargetARB.ElementArrayBuffer:
412 if (buffer != m_elementArrayBuffer) {
413 GL.BindBuffer(target, uBuffer);
414 m_elementArrayBuffer = buffer;
415 }
416 break;
417 default: GL.BindBuffer(target, uBuffer); break;
418 }
419 }
420
421 public static void BindFramebuffer(int framebuffer) {
422 if (framebuffer != m_framebuffer) {
423 GL.BindFramebuffer(FramebufferTarget.Framebuffer, (uint)framebuffer);
424 m_framebuffer = framebuffer;
425 }
426 }
427
428 public static void UseProgram(int program) {
429 if (program != m_program) {
430 GL.UseProgram((uint)program);
431 m_program = program;
432 }
433 }
434
435 public static void DeleteProgram(int program) {
436 if (m_program == program) {
437 m_program = -1;
438 }
439 GL.DeleteProgram((uint)program);
440 }
441
442 public static void DeleteTexture(int texture) {
443 if (m_texture2D == texture) {
444 m_texture2D = -1;
445 }
446 for (int i = 0; i < m_activeTexturesByUnit.Length; i++) {
447 if (m_activeTexturesByUnit[i] == texture) {
449 }
450 }
451 m_textureSamplerStates.Remove(texture);
452 GL.DeleteTexture((uint)texture);
453 }
454
455 public static void DeleteFramebuffer(int framebuffer) {
456 if (m_framebuffer == framebuffer) {
457 m_framebuffer = -1;
458 }
459 uint uFramebuffer = (uint)framebuffer;
460 GL.DeleteFramebuffers(1, in uFramebuffer);
461 }
462
463 public static void DeleteBuffer(BufferTargetARB target, int buffer) {
464 if (target == BufferTargetARB.ArrayBuffer) {
465 if (m_arrayBuffer == buffer) {
466 m_arrayBuffer = -1;
467 }
468 if (m_lastArrayBuffer == buffer) {
470 }
471 }
472 if (target == BufferTargetARB.ElementArrayBuffer
473 && m_elementArrayBuffer == buffer) {
475 }
476 uint uBuffer = (uint)buffer;
477 GL.DeleteBuffers(1u, in uBuffer);
478 }
479
480 public static void ApplyViewportScissor(Viewport viewport, Rectangle scissorRectangle, bool isScissorEnabled) {
481 if (!m_viewport.HasValue
482 || viewport.X != m_viewport.Value.X
483 || viewport.Y != m_viewport.Value.Y
484 || viewport.Width != m_viewport.Value.Width
485 || viewport.Height != m_viewport.Value.Height) {
486 int y = Display.RenderTarget == null ? Display.BackbufferSize.Y - viewport.Y - viewport.Height : viewport.Y;
487 GL.Viewport(viewport.X, y, (uint)viewport.Width, (uint)viewport.Height);
488 }
489 if (!m_viewport.HasValue
490 || viewport.MinDepth != m_viewport.Value.MinDepth
491 || viewport.MaxDepth != m_viewport.Value.MaxDepth) {
492 GL.DepthRange(viewport.MinDepth, viewport.MaxDepth);
493 }
494 m_viewport = viewport;
495 if (!isScissorEnabled) {
496 return;
497 }
498 if (m_scissorRectangle.HasValue) {
499 Rectangle value = scissorRectangle;
500 Rectangle? scissorRectangle2 = m_scissorRectangle;
501 if (!(value != scissorRectangle2)) {
502 return;
503 }
504 }
505 if (Display.RenderTarget == null) {
506 scissorRectangle.Top = Display.BackbufferSize.Y - scissorRectangle.Top - scissorRectangle.Height;
507 }
508 GL.Scissor(scissorRectangle.Left, scissorRectangle.Top, (uint)scissorRectangle.Width, (uint)scissorRectangle.Height);
509 m_scissorRectangle = scissorRectangle;
510 }
511
512 public static void ApplyRasterizerState(RasterizerState state) {
513 if (state != m_rasterizerState) {
514 m_rasterizerState = state;
515 switch (state.CullMode) {
516 case CullMode.None: Disable(EnableCap.CullFace); break;
517 case CullMode.CullClockwise:
518 Enable(EnableCap.CullFace);
519 CullFace(TriangleFace.Back);
520 FrontFace(Display.RenderTarget != null ? FrontFaceDirection.CW : FrontFaceDirection.Ccw);
521 break;
522 case CullMode.CullCounterClockwise:
523 Enable(EnableCap.CullFace);
524 CullFace(TriangleFace.Back);
525 FrontFace(Display.RenderTarget != null ? FrontFaceDirection.Ccw : FrontFaceDirection.CW);
526 break;
527 }
528 if (state.ScissorTestEnable) {
529 Enable(EnableCap.ScissorTest);
530 }
531 else {
532 Disable(EnableCap.ScissorTest);
533 }
534 if (state.DepthBias != 0f
535 || state.SlopeScaleDepthBias != 0f) {
536 Enable(EnableCap.PolygonOffsetFill);
538 }
539 else {
540 Disable(EnableCap.PolygonOffsetFill);
541 }
542 }
543 }
544
545 public static void ApplyDepthStencilState(DepthStencilState state) {
546 if (state == m_depthStencilState) {
547 return;
548 }
549 m_depthStencilState = state;
550 if (state.DepthBufferTestEnable
551 || state.DepthBufferWriteEnable) {
552 Enable(EnableCap.DepthTest);
555 }
556 else {
557 Disable(EnableCap.DepthTest);
558 }
559 }
560
561 public static void ApplyBlendState(BlendState state) {
562 if (state == m_blendState) {
563 return;
564 }
565 m_blendState = state;
566 if (state.ColorBlendFunction == BlendFunction.Add
567 && state.ColorSourceBlend == Blend.One
568 && state.ColorDestinationBlend == Blend.Zero
569 && state.AlphaBlendFunction == BlendFunction.Add
570 && state.AlphaSourceBlend == Blend.One
571 && state.AlphaDestinationBlend == Blend.Zero) {
572 Disable(EnableCap.Blend);
573 return;
574 }
575 BlendEquationModeEXT all = TranslateBlendFunction(state.ColorBlendFunction);
576 BlendEquationModeEXT all2 = TranslateBlendFunction(state.AlphaBlendFunction);
577 BlendingFactor all3 = TranslateBlendSrc(state.ColorSourceBlend);
578 BlendingFactor all4 = TranslateBlendDest(state.ColorDestinationBlend);
579 BlendingFactor all5 = TranslateBlendSrc(state.AlphaSourceBlend);
580 BlendingFactor all6 = TranslateBlendDest(state.AlphaDestinationBlend);
581 if (all == all2
582 && all3 == all5
583 && all4 == all6) {
584 BlendEquation(all);
585 BlendFunc(all3, all4);
586 }
587 else {
588 BlendEquationSeparate(all, all2);
589 BlendFuncSeparate(all3, all4, all5, all6);
590 }
591 BlendColor(state.BlendFactor);
592 Enable(EnableCap.Blend);
593 }
594
595 public static void ApplyRenderTarget(RenderTarget2D renderTarget) {
596 if (renderTarget != null) {
597 BindFramebuffer(renderTarget.m_frameBuffer);
598 if (renderTarget.m_depthBuffer != 0) {
599 GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, (uint)renderTarget.m_depthBuffer);
600 }
601 }
602 else {
604 GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, (uint)m_mainDepthbuffer);
605 }
606 }
607
608 public static unsafe void ApplyShaderAndBuffers(Shader shader,
609 VertexDeclaration vertexDeclaration,
610 IntPtr vertexOffset,
611 int arrayBuffer,
612 int? elementArrayBuffer) {
613
614#if IOS && DEBUG
615 string log = GL.GetProgramInfoLog((uint)shader.m_program);
616 if(!string.IsNullOrEmpty(log)) Console.WriteLine("Program Link Error: " + log);
617 log = GL.GetShaderInfoLog((uint)shader.m_program);
618 if (!string.IsNullOrEmpty(log)) Console.WriteLine("Shader Compile Error: " + log);
619#endif
620
621
622 shader.PrepareForDrawing();
623 BindBuffer(BufferTargetARB.ArrayBuffer, arrayBuffer);
624 if (elementArrayBuffer.HasValue) {
625 BindBuffer(BufferTargetARB.ElementArrayBuffer, elementArrayBuffer.Value);
626 }
627 UseProgram(shader.m_program);
628 if (shader != m_lastShader
629 || vertexOffset != m_lastVertexOffset
630 || arrayBuffer != m_lastArrayBuffer
631 || vertexDeclaration.m_elements != m_lastVertexDeclaration.m_elements) {
632 Shader.VertexAttributeData[] vertexAttribData = shader.GetVertexAttribData(vertexDeclaration);
633 for (int i = 0; i < vertexAttribData.Length; i++) {
634 if (vertexAttribData[i].Size != 0) {
635 GL.VertexAttribPointer(
636 (uint)i,
637 vertexAttribData[i].Size,
638 vertexAttribData[i].Type,
639 vertexAttribData[i].Normalize,
640 (uint)vertexDeclaration.VertexStride,
641 (vertexOffset + vertexAttribData[i].Offset).ToPointer()
642 );
643 VertexAttribArray(i, true);
644 }
645 else {
646 VertexAttribArray(i, false);
647 }
648 }
649 m_lastShader = shader;
650 m_lastVertexDeclaration = vertexDeclaration;
651 m_lastVertexOffset = vertexOffset;
652 m_lastArrayBuffer = arrayBuffer;
653 }
654 int num = 0;
655 int num2 = 0;
656 ShaderParameter shaderParameter;
657 while (true) {
658 if (num2 >= shader.m_parameters.Length) {
659 return;
660 }
661 shaderParameter = shader.m_parameters[num2];
662 if (shaderParameter.IsChanged) {
663 switch (shaderParameter.Type) {
664 case ShaderParameterType.Float:
665 GL.Uniform1(shaderParameter.Location, (uint)shaderParameter.Count, shaderParameter.Value);
666 shaderParameter.IsChanged = false;
667 break;
668 case ShaderParameterType.Vector2:
669 GL.Uniform2(shaderParameter.Location, (uint)shaderParameter.Count, shaderParameter.Value);
670 shaderParameter.IsChanged = false;
671 break;
672 case ShaderParameterType.Vector3:
673 GL.Uniform3(shaderParameter.Location, (uint)shaderParameter.Count, shaderParameter.Value);
674 shaderParameter.IsChanged = false;
675 break;
676 case ShaderParameterType.Vector4:
677 GL.Uniform4(shaderParameter.Location, (uint)shaderParameter.Count, shaderParameter.Value);
678 shaderParameter.IsChanged = false;
679 break;
680 case ShaderParameterType.Matrix:
681 GL.UniformMatrix4(shaderParameter.Location, (uint)shaderParameter.Count, false, shaderParameter.Value);
682 shaderParameter.IsChanged = false;
683 break;
684 default: throw new InvalidOperationException("Unsupported shader parameter type.");
685 case ShaderParameterType.Texture2D:
686 case ShaderParameterType.Sampler2D: break;
687 }
688 }
689 if (shaderParameter.Type == ShaderParameterType.Texture2D) {
691 throw new InvalidOperationException("Too many simultaneous textures.");
692 }
693 ActiveTexture(TextureUnit.Texture0 + num);
694 if (shaderParameter.IsChanged) {
695 GL.Uniform1(shaderParameter.Location, num);
696 }
697 ShaderParameter obj = shader.m_parameters[num2 + 1];
698 Texture2D texture2D = (Texture2D)shaderParameter.Resource;
699 SamplerState samplerState = (SamplerState)obj.Resource;
700 if (texture2D != null) {
701 if (samplerState == null) {
702 break;
703 }
704 if (m_activeTexturesByUnit[num] != texture2D.m_texture) {
705 BindTexture(TextureTarget.Texture2D, texture2D.m_texture, true);
706 }
707 if (!m_textureSamplerStates.TryGetValue(texture2D.m_texture, out SamplerState value)
708 || value != samplerState) {
709 BindTexture(TextureTarget.Texture2D, texture2D.m_texture, false);
711 GL.TexParameter(
712 TextureTarget.Texture2D,
713 TextureParameterName.TextureMaxAnisotropy,
714 samplerState.FilterMode == TextureFilterMode.Anisotropic ? samplerState.MaxAnisotropy : 1f
715 );
716 }
717 GL.TexParameter(
718 TextureTarget.Texture2D,
719 TextureParameterName.TextureMinFilter,
720 (int)TranslateTextureFilterModeMin(samplerState.FilterMode, texture2D.MipLevelsCount > 1)
721 );
722 GL.TexParameter(
723 TextureTarget.Texture2D,
724 TextureParameterName.TextureMagFilter,
726 );
727 GL.TexParameter(
728 TextureTarget.Texture2D,
729 TextureParameterName.TextureWrapS,
731 );
732 GL.TexParameter(
733 TextureTarget.Texture2D,
734 TextureParameterName.TextureWrapT,
736 );
737#if !MOBILE && !BROWSER
738 GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinLod, samplerState.MinLod);
739 GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLod, samplerState.MaxLod);
740#endif
741 m_textureSamplerStates[texture2D.m_texture] = samplerState;
742 }
743 }
744 else if (m_activeTexturesByUnit[num] != 0) {
745 BindTexture(TextureTarget.Texture2D, 0, true);
746 }
747 num++;
748 shaderParameter.IsChanged = false;
749 }
750 num2++;
751 }
752 throw new InvalidOperationException($"Associated SamplerState is not set for texture \"{shaderParameter.Name}\".");
753 }
754
755 public static void Clear(RenderTarget2D renderTarget, Vector4? color, float? depth, int? stencil) {
756 ClearBufferMask all = ClearBufferMask.None;
757 if (color.HasValue) {
758 all |= ClearBufferMask.ColorBufferBit;
759 ClearColor(color.Value);
760 ColorMask(0xF);
761 }
762 if (depth.HasValue) {
763 all |= ClearBufferMask.DepthBufferBit;
764 ClearDepth(depth.Value);
765 if (DepthMask(true)) {
766 m_depthStencilState = null;
767 }
768 }
769 if (stencil.HasValue) {
770 all |= ClearBufferMask.StencilBufferBit;
771 ClearStencil(stencil.Value);
772 }
773 if (all != ClearBufferMask.None) {
774 ApplyRenderTarget(renderTarget);
775 if (Disable(EnableCap.ScissorTest)) {
776 m_rasterizerState = null;
777 }
778 GL.Clear(all);
779 }
780 }
781
782 public static void HandleContextLost() {
783 try {
784 Log.Information("Device lost");
786 GC.Collect();
788 Display.Resize();
790 Log.Information("Device reset");
791 }
792 catch (Exception ex) {
793 Log.Error("Failed to recreate graphics resources. Reason: {0}", ex.Message);
794 }
795 }
796
797 public static float LineWidth {
798 get {
799 GL.GetFloat(GetPName.LineWidth, out float width);
800 return width == 0f ? 1f : width;
801 }
802 set => GL.LineWidth(value);
803 }
804
805 public static void TranslateVertexElementFormat(VertexElementFormat vertexElementFormat,
806 out VertexAttribPointerType type,
807 out bool normalize) {
808 switch (vertexElementFormat) {
809 case VertexElementFormat.Single:
810 type = VertexAttribPointerType.Float;
811 normalize = false;
812 break;
813 case VertexElementFormat.Vector2:
814 type = VertexAttribPointerType.Float;
815 normalize = false;
816 break;
817 case VertexElementFormat.Vector3:
818 type = VertexAttribPointerType.Float;
819 normalize = false;
820 break;
821 case VertexElementFormat.Vector4:
822 type = VertexAttribPointerType.Float;
823 normalize = false;
824 break;
825 case VertexElementFormat.Byte4:
826 type = VertexAttribPointerType.UnsignedByte;
827 normalize = false;
828 break;
829 case VertexElementFormat.NormalizedByte4:
830 type = VertexAttribPointerType.UnsignedByte;
831 normalize = true;
832 break;
833 case VertexElementFormat.Short2:
834 type = VertexAttribPointerType.Short;
835 normalize = false;
836 break;
837 case VertexElementFormat.NormalizedShort2:
838 type = VertexAttribPointerType.Short;
839 normalize = true;
840 break;
841 case VertexElementFormat.Short4:
842 type = VertexAttribPointerType.Short;
843 normalize = false;
844 break;
845 case VertexElementFormat.NormalizedShort4:
846 type = VertexAttribPointerType.Short;
847 normalize = true;
848 break;
849 default: throw new InvalidOperationException("Unsupported vertex element format.");
850 }
851 }
852
853 public static DrawElementsType TranslateIndexFormat(IndexFormat indexFormat) {
854 return indexFormat switch {
855 IndexFormat.SixteenBits => DrawElementsType.UnsignedShort,
856 IndexFormat.ThirtyTwoBits => DrawElementsType.UnsignedInt,
857 _ => throw new InvalidOperationException("Unsupported index format.")
858 };
859 }
860
861 public static ShaderParameterType TranslateActiveUniformType(UniformType type) {
862 return type switch {
863 UniformType.Float => ShaderParameterType.Float,
864 UniformType.FloatVec2 => ShaderParameterType.Vector2,
865 UniformType.FloatVec3 => ShaderParameterType.Vector3,
866 UniformType.FloatVec4 => ShaderParameterType.Vector4,
867 UniformType.FloatMat4 => ShaderParameterType.Matrix,
868 UniformType.Sampler2D => ShaderParameterType.Texture2D,
869 _ => throw new InvalidOperationException("Unsupported shader parameter type.")
870 };
871 }
872
873 public static Silk.NET.OpenGLES.PrimitiveType TranslatePrimitiveType(PrimitiveType primitiveType) {
874 return primitiveType switch {
875 PrimitiveType.LineList => Silk.NET.OpenGLES.PrimitiveType.Lines,
876 PrimitiveType.LineStrip => Silk.NET.OpenGLES.PrimitiveType.LineStrip,
877 PrimitiveType.TriangleList => Silk.NET.OpenGLES.PrimitiveType.Triangles,
878 PrimitiveType.TriangleStrip => Silk.NET.OpenGLES.PrimitiveType.TriangleStrip,
879 PrimitiveType.Points => Silk.NET.OpenGLES.PrimitiveType.Points,
880 PrimitiveType.LineLoop => Silk.NET.OpenGLES.PrimitiveType.LineLoop,
881 PrimitiveType.TriangleFan => Silk.NET.OpenGLES.PrimitiveType.TriangleFan,
882 _ => throw new InvalidOperationException("Unsupported primitive type.")
883 };
884 }
885
886 public static TextureMinFilter TranslateTextureFilterModeMin(TextureFilterMode filterMode, bool isMipmapped) {
887 switch (filterMode) {
888 case TextureFilterMode.Point:
889 if (!isMipmapped) {
890 return TextureMinFilter.Nearest;
891 }
892 return TextureMinFilter.NearestMipmapNearest;
893 case TextureFilterMode.Linear:
894 if (!isMipmapped) {
895 return TextureMinFilter.Linear;
896 }
897 return TextureMinFilter.LinearMipmapLinear;
898 case TextureFilterMode.Anisotropic:
899 if (!isMipmapped) {
900 return TextureMinFilter.Linear;
901 }
902 return TextureMinFilter.LinearMipmapLinear;
903 case TextureFilterMode.PointMipLinear:
904 if (!isMipmapped) {
905 return TextureMinFilter.Nearest;
906 }
907 return TextureMinFilter.NearestMipmapLinear;
908 case TextureFilterMode.LinearMipPoint:
909 if (!isMipmapped) {
910 return TextureMinFilter.Linear;
911 }
912 return TextureMinFilter.LinearMipmapNearest;
913 case TextureFilterMode.MinPointMagLinearMipPoint:
914 if (!isMipmapped) {
915 return TextureMinFilter.Nearest;
916 }
917 return TextureMinFilter.NearestMipmapNearest;
918 case TextureFilterMode.MinPointMagLinearMipLinear:
919 if (!isMipmapped) {
920 return TextureMinFilter.Nearest;
921 }
922 return TextureMinFilter.NearestMipmapLinear;
923 case TextureFilterMode.MinLinearMagPointMipPoint:
924 if (!isMipmapped) {
925 return TextureMinFilter.Linear;
926 }
927 return TextureMinFilter.LinearMipmapNearest;
928 case TextureFilterMode.MinLinearMagPointMipLinear:
929 if (!isMipmapped) {
930 return TextureMinFilter.Linear;
931 }
932 return TextureMinFilter.LinearMipmapLinear;
933 default: throw new InvalidOperationException("Unsupported texture filter mode.");
934 }
935 }
936
937 public static TextureMagFilter TranslateTextureFilterModeMag(TextureFilterMode filterMode) {
938 return filterMode switch {
939 TextureFilterMode.Point => TextureMagFilter.Nearest,
940 TextureFilterMode.Linear => TextureMagFilter.Linear,
941 TextureFilterMode.Anisotropic => TextureMagFilter.Linear,
942 TextureFilterMode.PointMipLinear => TextureMagFilter.Nearest,
943 TextureFilterMode.LinearMipPoint => TextureMagFilter.Nearest,
944 TextureFilterMode.MinPointMagLinearMipPoint => TextureMagFilter.Linear,
945 TextureFilterMode.MinPointMagLinearMipLinear => TextureMagFilter.Linear,
946 TextureFilterMode.MinLinearMagPointMipPoint => TextureMagFilter.Nearest,
947 TextureFilterMode.MinLinearMagPointMipLinear => TextureMagFilter.Nearest,
948 _ => throw new InvalidOperationException("Unsupported texture filter mode.")
949 };
950 }
951
952 public static TextureWrapMode TranslateTextureAddressMode(TextureAddressMode addressMode) {
953 return addressMode switch {
954 TextureAddressMode.Clamp => TextureWrapMode.ClampToEdge,
955 TextureAddressMode.Wrap => TextureWrapMode.Repeat,
956 _ => throw new InvalidOperationException("Unsupported texture address mode.")
957 };
958 }
959
960 public static DepthFunction TranslateCompareFunction(CompareFunction compareFunction) {
961 return compareFunction switch {
962 CompareFunction.Always => DepthFunction.Always,
963 CompareFunction.Equal => DepthFunction.Equal,
964 CompareFunction.Greater => DepthFunction.Greater,
965 CompareFunction.GreaterEqual => DepthFunction.Gequal,
966 CompareFunction.Less => DepthFunction.Less,
967 CompareFunction.LessEqual => DepthFunction.Lequal,
968 CompareFunction.Never => DepthFunction.Never,
969 CompareFunction.NotEqual => DepthFunction.Notequal,
970 _ => throw new InvalidOperationException("Unsupported texture address mode.")
971 };
972 }
973
974 public static BlendEquationModeEXT TranslateBlendFunction(BlendFunction blendFunction) {
975 return blendFunction switch {
976 BlendFunction.Add => BlendEquationModeEXT.FuncAdd,
977 BlendFunction.Subtract => BlendEquationModeEXT.FuncSubtract,
978 BlendFunction.ReverseSubtract => BlendEquationModeEXT.FuncReverseSubtract,
979 _ => throw new InvalidOperationException("Unsupported blend function.")
980 };
981 }
982
983 public static BlendingFactor TranslateBlendSrc(Blend blend) {
984 return blend switch {
985 Blend.Zero => 0,
986 Blend.One => (BlendingFactor)1,
987 Blend.SourceColor => BlendingFactor.SrcColor,
988 Blend.InverseSourceColor => BlendingFactor.OneMinusSrcColor,
989 Blend.DestinationColor => BlendingFactor.DstColor,
990 Blend.InverseDestinationColor => BlendingFactor.OneMinusDstColor,
991 Blend.SourceAlpha => BlendingFactor.SrcAlpha,
992 Blend.InverseSourceAlpha => BlendingFactor.OneMinusSrcAlpha,
993 Blend.DestinationAlpha => BlendingFactor.DstAlpha,
994 Blend.InverseDestinationAlpha => BlendingFactor.OneMinusDstAlpha,
995 Blend.BlendFactor => BlendingFactor.ConstantColor,
996 Blend.InverseBlendFactor => BlendingFactor.OneMinusConstantColor,
997 Blend.SourceAlphaSaturation => BlendingFactor.SrcAlphaSaturate,
998 _ => throw new InvalidOperationException("Unsupported blend.")
999 };
1000 }
1001
1002 public static BlendingFactor TranslateBlendDest(Blend blend) {
1003 return blend switch {
1004 Blend.Zero => 0,
1005 Blend.One => (BlendingFactor)1,
1006 Blend.SourceColor => BlendingFactor.SrcColor,
1007 Blend.InverseSourceColor => BlendingFactor.OneMinusSrcColor,
1008 Blend.DestinationColor => BlendingFactor.DstColor,
1009 Blend.InverseDestinationColor => BlendingFactor.OneMinusDstColor,
1010 Blend.SourceAlpha => BlendingFactor.SrcAlpha,
1011 Blend.InverseSourceAlpha => BlendingFactor.OneMinusSrcAlpha,
1012 Blend.DestinationAlpha => BlendingFactor.DstAlpha,
1013 Blend.InverseDestinationAlpha => BlendingFactor.OneMinusDstAlpha,
1014 Blend.BlendFactor => BlendingFactor.ConstantColor,
1015 Blend.InverseBlendFactor => BlendingFactor.OneMinusConstantColor,
1016 Blend.SourceAlphaSaturation => BlendingFactor.SrcAlphaSaturate,
1017 _ => throw new InvalidOperationException("Unsupported blend.")
1018 };
1019 }
1020
1021 public static InternalFormat TranslateDepthFormat(DepthFormat depthFormat) {
1022 return depthFormat switch {
1023 DepthFormat.Depth16 => InternalFormat.DepthComponent16,
1024#if MOBILE
1025 DepthFormat.Depth24Stencil8 => GL_OES_packed_depth_stencil ? InternalFormat.Depth24Stencil8 : InternalFormat.DepthComponent16,
1026#else
1027 DepthFormat.Depth24Stencil8 => InternalFormat.Depth24Stencil8,
1028#endif
1029 _ => throw new InvalidOperationException("Unsupported DepthFormat.")
1030 };
1031 }
1032#if DEBUG && !IOS
1033 public static void DebugMessageDelegate (GLEnum source, GLEnum type, int id, GLEnum severity, int length, nint message, nint userParam) {
1034 if (type == GLEnum.DebugTypeOther) {
1035 return;
1036 }
1037 string messageText = Marshal.PtrToStringAnsi(message, length);
1038 Console.WriteLine($"[{type.ToString().Substring(9)}] {messageText}");
1039 if (type == GLEnum.DebugTypeError) {
1040 Debugger.Break();
1041 }
1042 }
1043#endif
1044 [Conditional("DEBUG")]
1045 public static void CheckGLError() { }
1046 }
1047}
unsafe
定义 Main.cs:15
static void HandleDeviceLost()
static void HandleDeviceReset()
static RenderTarget2D RenderTarget
static IntPtr CreateContext(IntPtr dpy, IntPtr config, IntPtr shareContext, int[] attribList)
const int DepthSize
定义 EGL.cs:15
static bool MakeCurrent(IntPtr dpy, IntPtr draw, IntPtr read, IntPtr ctx)
static IntPtr GetProcAddress(string proc)
static bool ChooseConfig(IntPtr dpy, int[] attribList, IntPtr[] configs, int configSize, out int numConfig)
const int GreenSize
定义 EGL.cs:12
const int OpenglEs3Bit
定义 EGL.cs:22
const int AlphaSize
定义 EGL.cs:14
static IntPtr CreateWindowSurface(IntPtr dpy, IntPtr config, IntPtr nativeWindow, int[] attribList)
const int RenderableType
定义 EGL.cs:18
const int SurfaceType
定义 EGL.cs:17
const int BlueSize
定义 EGL.cs:13
static IntPtr GetDisplay(IntPtr displayId)
const int StencilSize
定义 EGL.cs:16
const int RedSize
定义 EGL.cs:11
const int ContextClientVersion
定义 EGL.cs:23
const int WindowBit
定义 EGL.cs:20
static bool Initialize(IntPtr dpy, out int major, out int minor)
static FrontFaceDirection m_frontFace
static int[] m_activeTexturesByUnit
static RasterizerState m_rasterizerState
static BlendingFactor m_blendFuncSource
static BlendingFactor TranslateBlendSrc(Blend blend)
static void TranslateVertexElementFormat(VertexElementFormat vertexElementFormat, out VertexAttribPointerType type, out bool normalize)
static DepthStencilState m_depthStencilState
static void DeleteFramebuffer(int framebuffer)
static void ClearStencil(int stencil)
static BlendEquationModeEXT m_blendEquation
static BlendingFactor m_blendFuncSourceColor
static BlendEquationModeEXT m_blendEquationColor
static TriangleFace m_cullFace
static BlendingFactor m_blendFuncSourceAlpha
static bool GL_KHR_texture_compression_astc_ldr
static void ColorMask(int colorMask)
static BlendState m_blendState
static TextureMinFilter TranslateTextureFilterModeMin(TextureFilterMode filterMode, bool isMipmapped)
static ? Rectangle m_scissorRectangle
static void DeleteBuffer(BufferTargetARB target, int buffer)
static DepthFunction TranslateCompareFunction(CompareFunction compareFunction)
static ? Vector4 m_clearColor
static void BlendColor(Vector4 blendColor)
static void ApplyDepthStencilState(DepthStencilState state)
static void UseProgram(int program)
static BlendingFactor m_blendFuncDestination
static bool Enable(EnableCap state)
static void CullFace(TriangleFace cullFace)
static DepthFunction m_depthFunction
static void DeleteProgram(int program)
static int GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
static ? bool[] m_vertexAttribArray
static void ClearColor(Vector4 color)
static ShaderParameterType TranslateActiveUniformType(UniformType type)
static bool GL_EXT_texture_filter_anisotropic
static void ApplyRasterizerState(RasterizerState state)
static void PolygonOffset(float factor, float units)
static BlendEquationModeEXT m_blendEquationAlpha
static TextureMagFilter TranslateTextureFilterModeMag(TextureFilterMode filterMode)
static void BindFramebuffer(int framebuffer)
static void Clear(RenderTarget2D renderTarget, Vector4? color, float? depth, int? stencil)
static BlendingFactor TranslateBlendDest(Blend blend)
static void DepthFunc(DepthFunction depthFunction)
static void VertexAttribArray(int index, bool enable)
static void ActiveTexture(TextureUnit textureUnit)
static void ApplyViewportScissor(Viewport viewport, Rectangle scissorRectangle, bool isScissorEnabled)
static void ApplyBlendState(BlendState state)
static TextureUnit m_activeTextureUnit
static void BlendFuncSeparate(BlendingFactor blendFuncSourceColor, BlendingFactor blendFuncDestinationColor, BlendingFactor blendFuncSourceAlpha, BlendingFactor blendFuncDestinationAlpha)
static TextureWrapMode TranslateTextureAddressMode(TextureAddressMode addressMode)
static Silk.NET.OpenGLES.PrimitiveType TranslatePrimitiveType(PrimitiveType primitiveType)
static Dictionary< int, SamplerState > m_textureSamplerStates
static BlendingFactor m_blendFuncDestinationAlpha
static void BlendEquationSeparate(BlendEquationModeEXT blendEquationColor, BlendEquationModeEXT blendEquationAlpha)
static BlendingFactor m_blendFuncDestinationColor
static bool GL_OES_packed_depth_stencil
static bool DepthMask(bool depthMask)
static void BindBuffer(BufferTargetARB target, int buffer)
static bool IsEnabled(EnableCap state)
static unsafe void ApplyShaderAndBuffers(Shader shader, VertexDeclaration vertexDeclaration, IntPtr vertexOffset, int arrayBuffer, int? elementArrayBuffer)
static DrawElementsType TranslateIndexFormat(IndexFormat indexFormat)
static ? Viewport m_viewport
static VertexDeclaration m_lastVertexDeclaration
static void ApplyRenderTarget(RenderTarget2D renderTarget)
static void FrontFace(FrontFaceDirection frontFace)
static BlendEquationModeEXT TranslateBlendFunction(BlendFunction blendFunction)
static void BlendEquation(BlendEquationModeEXT blendEquation)
static void BindTexture(TextureTarget target, int texture, bool forceBind)
static InternalFormat TranslateDepthFormat(DepthFormat depthFormat)
static void ClearDepth(float depth)
static bool Disable(EnableCap state)
static void DeleteTexture(int texture)
static Dictionary< EnableCap, bool > m_enableDisableStates
static void BlendFunc(BlendingFactor blendFuncSource, BlendingFactor blendFuncDestination)
virtual VertexAttributeData[] GetVertexAttribData(VertexDeclaration vertexDeclaration)
ShaderParameter[] m_parameters
virtual void PrepareForDrawing()
readonly ShaderParameterType Type
static void Error(object message)
定义 Log.cs:80
static void Information(object message)
定义 Log.cs:56
static IntPtr Handle
static IView m_view