OpenGlPage.xaml.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Numerics;
  6. using System.Runtime.InteropServices;
  7. using Avalonia;
  8. using Avalonia.Controls;
  9. using Avalonia.OpenGL;
  10. using Avalonia.OpenGL.Controls;
  11. using Avalonia.Platform.Interop;
  12. using Avalonia.Threading;
  13. using static Avalonia.OpenGL.GlConsts;
  14. // ReSharper disable StringLiteralTypo
  15. namespace ControlCatalog.Pages
  16. {
  17. public class OpenGlPage : UserControl
  18. {
  19. }
  20. public class OpenGlPageControl : OpenGlControlBase
  21. {
  22. private float _yaw;
  23. public static readonly DirectProperty<OpenGlPageControl, float> YawProperty =
  24. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Yaw", o => o.Yaw, (o, v) => o.Yaw = v);
  25. public float Yaw
  26. {
  27. get => _yaw;
  28. set => SetAndRaise(YawProperty, ref _yaw, value);
  29. }
  30. private float _pitch;
  31. public static readonly DirectProperty<OpenGlPageControl, float> PitchProperty =
  32. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Pitch", o => o.Pitch, (o, v) => o.Pitch = v);
  33. public float Pitch
  34. {
  35. get => _pitch;
  36. set => SetAndRaise(PitchProperty, ref _pitch, value);
  37. }
  38. private float _roll;
  39. public static readonly DirectProperty<OpenGlPageControl, float> RollProperty =
  40. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Roll", o => o.Roll, (o, v) => o.Roll = v);
  41. public float Roll
  42. {
  43. get => _roll;
  44. set => SetAndRaise(RollProperty, ref _roll, value);
  45. }
  46. private float _disco;
  47. public static readonly DirectProperty<OpenGlPageControl, float> DiscoProperty =
  48. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Disco", o => o.Disco, (o, v) => o.Disco = v);
  49. public float Disco
  50. {
  51. get => _disco;
  52. set => SetAndRaise(DiscoProperty, ref _disco, value);
  53. }
  54. private string _info;
  55. public static readonly DirectProperty<OpenGlPageControl, string> InfoProperty =
  56. AvaloniaProperty.RegisterDirect<OpenGlPageControl, string>("Info", o => o.Info, (o, v) => o.Info = v);
  57. public string Info
  58. {
  59. get => _info;
  60. private set => SetAndRaise(InfoProperty, ref _info, value);
  61. }
  62. static OpenGlPageControl()
  63. {
  64. AffectsRender<OpenGlPageControl>(YawProperty, PitchProperty, RollProperty, DiscoProperty);
  65. }
  66. private int _vertexShader;
  67. private int _fragmentShader;
  68. private int _shaderProgram;
  69. private int _vertexBufferObject;
  70. private int _indexBufferObject;
  71. private int _vertexArrayObject;
  72. private GlExtrasInterface _glExt;
  73. private string GetShader(bool fragment, string shader)
  74. {
  75. var version = (GlVersion.Type == GlProfileType.OpenGL ?
  76. RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 150 : 120 :
  77. 100);
  78. var data = "#version " + version + "\n";
  79. if (GlVersion.Type == GlProfileType.OpenGLES)
  80. data += "precision mediump float;\n";
  81. if (version >= 150)
  82. {
  83. shader = shader.Replace("attribute", "in");
  84. if (fragment)
  85. shader = shader
  86. .Replace("varying", "in")
  87. .Replace("//DECLAREGLFRAG", "out vec4 outFragColor;")
  88. .Replace("gl_FragColor", "outFragColor");
  89. else
  90. shader = shader.Replace("varying", "out");
  91. }
  92. data += shader;
  93. return data;
  94. }
  95. private string VertexShaderSource => GetShader(false, @"
  96. attribute vec3 aPos;
  97. attribute vec3 aNormal;
  98. uniform mat4 uModel;
  99. uniform mat4 uProjection;
  100. uniform mat4 uView;
  101. varying vec3 FragPos;
  102. varying vec3 VecPos;
  103. varying vec3 Normal;
  104. uniform float uTime;
  105. uniform float uDisco;
  106. void main()
  107. {
  108. float discoScale = sin(uTime * 10.0) / 10.0;
  109. float distortionX = 1.0 + uDisco * cos(uTime * 20.0) / 10.0;
  110. float scale = 1.0 + uDisco * discoScale;
  111. vec3 scaledPos = aPos;
  112. scaledPos.x = scaledPos.x * distortionX;
  113. scaledPos *= scale;
  114. gl_Position = uProjection * uView * uModel * vec4(scaledPos, 1.0);
  115. FragPos = vec3(uModel * vec4(aPos, 1.0));
  116. VecPos = aPos;
  117. Normal = normalize(vec3(uModel * vec4(aNormal, 1.0)));
  118. }
  119. ");
  120. private string FragmentShaderSource => GetShader(true, @"
  121. varying vec3 FragPos;
  122. varying vec3 VecPos;
  123. varying vec3 Normal;
  124. uniform float uMaxY;
  125. uniform float uMinY;
  126. uniform float uTime;
  127. uniform float uDisco;
  128. //DECLAREGLFRAG
  129. void main()
  130. {
  131. float y = (VecPos.y - uMinY) / (uMaxY - uMinY);
  132. float c = cos(atan(VecPos.x, VecPos.z) * 20.0 + uTime * 40.0 + y * 50.0);
  133. float s = sin(-atan(VecPos.z, VecPos.x) * 20.0 - uTime * 20.0 - y * 30.0);
  134. vec3 discoColor = vec3(
  135. 0.5 + abs(0.5 - y) * cos(uTime * 10.0),
  136. 0.25 + (smoothstep(0.3, 0.8, y) * (0.5 - c / 4.0)),
  137. 0.25 + abs((smoothstep(0.1, 0.4, y) * (0.5 - s / 4.0))));
  138. vec3 objectColor = vec3((1.0 - y), 0.40 + y / 4.0, y * 0.75 + 0.25);
  139. objectColor = objectColor * (1.0 - uDisco) + discoColor * uDisco;
  140. float ambientStrength = 0.3;
  141. vec3 lightColor = vec3(1.0, 1.0, 1.0);
  142. vec3 lightPos = vec3(uMaxY * 2.0, uMaxY * 2.0, uMaxY * 2.0);
  143. vec3 ambient = ambientStrength * lightColor;
  144. vec3 norm = normalize(Normal);
  145. vec3 lightDir = normalize(lightPos - FragPos);
  146. float diff = max(dot(norm, lightDir), 0.0);
  147. vec3 diffuse = diff * lightColor;
  148. vec3 result = (ambient + diffuse) * objectColor;
  149. gl_FragColor = vec4(result, 1.0);
  150. }
  151. ");
  152. [StructLayout(LayoutKind.Sequential, Pack = 4)]
  153. private struct Vertex
  154. {
  155. public Vector3 Position;
  156. public Vector3 Normal;
  157. }
  158. private readonly Vertex[] _points;
  159. private readonly ushort[] _indices;
  160. private readonly float _minY;
  161. private readonly float _maxY;
  162. public OpenGlPageControl()
  163. {
  164. var name = typeof(OpenGlPage).Assembly.GetManifestResourceNames().First(x => x.Contains("teapot.bin"));
  165. using (var sr = new BinaryReader(typeof(OpenGlPage).Assembly.GetManifestResourceStream(name)))
  166. {
  167. var buf = new byte[sr.ReadInt32()];
  168. sr.Read(buf, 0, buf.Length);
  169. var points = new float[buf.Length / 4];
  170. Buffer.BlockCopy(buf, 0, points, 0, buf.Length);
  171. buf = new byte[sr.ReadInt32()];
  172. sr.Read(buf, 0, buf.Length);
  173. _indices = new ushort[buf.Length / 2];
  174. Buffer.BlockCopy(buf, 0, _indices, 0, buf.Length);
  175. _points = new Vertex[points.Length / 3];
  176. for (var primitive = 0; primitive < points.Length / 3; primitive++)
  177. {
  178. var srci = primitive * 3;
  179. _points[primitive] = new Vertex
  180. {
  181. Position = new Vector3(points[srci], points[srci + 1], points[srci + 2])
  182. };
  183. }
  184. for (int i = 0; i < _indices.Length; i += 3)
  185. {
  186. Vector3 a = _points[_indices[i]].Position;
  187. Vector3 b = _points[_indices[i + 1]].Position;
  188. Vector3 c = _points[_indices[i + 2]].Position;
  189. var normal = Vector3.Normalize(Vector3.Cross(c - b, a - b));
  190. _points[_indices[i]].Normal += normal;
  191. _points[_indices[i + 1]].Normal += normal;
  192. _points[_indices[i + 2]].Normal += normal;
  193. }
  194. for (int i = 0; i < _points.Length; i++)
  195. {
  196. _points[i].Normal = Vector3.Normalize(_points[i].Normal);
  197. _maxY = Math.Max(_maxY, _points[i].Position.Y);
  198. _minY = Math.Min(_minY, _points[i].Position.Y);
  199. }
  200. }
  201. }
  202. private void CheckError(GlInterface gl)
  203. {
  204. int err;
  205. while ((err = gl.GetError()) != GL_NO_ERROR)
  206. Console.WriteLine(err);
  207. }
  208. protected unsafe override void OnOpenGlInit(GlInterface GL, int fb)
  209. {
  210. CheckError(GL);
  211. _glExt = new GlExtrasInterface(GL);
  212. Info = $"Renderer: {GL.GetString(GL_RENDERER)} Version: {GL.GetString(GL_VERSION)}";
  213. // Load the source of the vertex shader and compile it.
  214. _vertexShader = GL.CreateShader(GL_VERTEX_SHADER);
  215. Console.WriteLine(GL.CompileShaderAndGetError(_vertexShader, VertexShaderSource));
  216. // Load the source of the fragment shader and compile it.
  217. _fragmentShader = GL.CreateShader(GL_FRAGMENT_SHADER);
  218. Console.WriteLine(GL.CompileShaderAndGetError(_fragmentShader, FragmentShaderSource));
  219. // Create the shader program, attach the vertex and fragment shaders and link the program.
  220. _shaderProgram = GL.CreateProgram();
  221. GL.AttachShader(_shaderProgram, _vertexShader);
  222. GL.AttachShader(_shaderProgram, _fragmentShader);
  223. const int positionLocation = 0;
  224. const int normalLocation = 1;
  225. GL.BindAttribLocationString(_shaderProgram, positionLocation, "aPos");
  226. GL.BindAttribLocationString(_shaderProgram, normalLocation, "aNormal");
  227. Console.WriteLine(GL.LinkProgramAndGetError(_shaderProgram));
  228. CheckError(GL);
  229. // Create the vertex buffer object (VBO) for the vertex data.
  230. _vertexBufferObject = GL.GenBuffer();
  231. // Bind the VBO and copy the vertex data into it.
  232. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  233. CheckError(GL);
  234. var vertexSize = Marshal.SizeOf<Vertex>();
  235. fixed (void* pdata = _points)
  236. GL.BufferData(GL_ARRAY_BUFFER, new IntPtr(_points.Length * vertexSize),
  237. new IntPtr(pdata), GL_STATIC_DRAW);
  238. _indexBufferObject = GL.GenBuffer();
  239. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  240. CheckError(GL);
  241. fixed (void* pdata = _indices)
  242. GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, new IntPtr(_indices.Length * sizeof(ushort)), new IntPtr(pdata),
  243. GL_STATIC_DRAW);
  244. CheckError(GL);
  245. _vertexArrayObject = _glExt.GenVertexArray();
  246. _glExt.BindVertexArray(_vertexArrayObject);
  247. CheckError(GL);
  248. GL.VertexAttribPointer(positionLocation, 3, GL_FLOAT,
  249. 0, vertexSize, IntPtr.Zero);
  250. GL.VertexAttribPointer(normalLocation, 3, GL_FLOAT,
  251. 0, vertexSize, new IntPtr(12));
  252. GL.EnableVertexAttribArray(positionLocation);
  253. GL.EnableVertexAttribArray(normalLocation);
  254. CheckError(GL);
  255. }
  256. protected override void OnOpenGlDeinit(GlInterface GL, int fb)
  257. {
  258. // Unbind everything
  259. GL.BindBuffer(GL_ARRAY_BUFFER, 0);
  260. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  261. _glExt.BindVertexArray(0);
  262. GL.UseProgram(0);
  263. // Delete all resources.
  264. GL.DeleteBuffers(2, new[] { _vertexBufferObject, _indexBufferObject });
  265. _glExt.DeleteVertexArrays(1, new[] { _vertexArrayObject });
  266. GL.DeleteProgram(_shaderProgram);
  267. GL.DeleteShader(_fragmentShader);
  268. GL.DeleteShader(_vertexShader);
  269. }
  270. static Stopwatch St = Stopwatch.StartNew();
  271. protected override unsafe void OnOpenGlRender(GlInterface gl, int fb)
  272. {
  273. gl.ClearColor(0, 0, 0, 0);
  274. gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  275. gl.Enable(GL_DEPTH_TEST);
  276. gl.Viewport(0, 0, (int)Bounds.Width, (int)Bounds.Height);
  277. var GL = gl;
  278. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  279. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  280. _glExt.BindVertexArray(_vertexArrayObject);
  281. GL.UseProgram(_shaderProgram);
  282. CheckError(GL);
  283. var projection =
  284. Matrix4x4.CreatePerspectiveFieldOfView((float)(Math.PI / 4), (float)(Bounds.Width / Bounds.Height),
  285. 0.01f, 1000);
  286. var view = Matrix4x4.CreateLookAt(new Vector3(25, 25, 25), new Vector3(), new Vector3(0, -1, 0));
  287. var model = Matrix4x4.CreateFromYawPitchRoll(_yaw, _pitch, _roll);
  288. var modelLoc = GL.GetUniformLocationString(_shaderProgram, "uModel");
  289. var viewLoc = GL.GetUniformLocationString(_shaderProgram, "uView");
  290. var projectionLoc = GL.GetUniformLocationString(_shaderProgram, "uProjection");
  291. var maxYLoc = GL.GetUniformLocationString(_shaderProgram, "uMaxY");
  292. var minYLoc = GL.GetUniformLocationString(_shaderProgram, "uMinY");
  293. var timeLoc = GL.GetUniformLocationString(_shaderProgram, "uTime");
  294. var discoLoc = GL.GetUniformLocationString(_shaderProgram, "uDisco");
  295. GL.UniformMatrix4fv(modelLoc, 1, false, &model);
  296. GL.UniformMatrix4fv(viewLoc, 1, false, &view);
  297. GL.UniformMatrix4fv(projectionLoc, 1, false, &projection);
  298. GL.Uniform1f(maxYLoc, _maxY);
  299. GL.Uniform1f(minYLoc, _minY);
  300. GL.Uniform1f(timeLoc, (float)St.Elapsed.TotalSeconds);
  301. GL.Uniform1f(discoLoc, _disco);
  302. CheckError(GL);
  303. GL.DrawElements(GL_TRIANGLES, _indices.Length, GL_UNSIGNED_SHORT, IntPtr.Zero);
  304. CheckError(GL);
  305. if (_disco > 0.01)
  306. Dispatcher.UIThread.Post(InvalidateVisual, DispatcherPriority.Background);
  307. }
  308. class GlExtrasInterface : GlInterfaceBase<GlInterface.GlContextInfo>
  309. {
  310. public GlExtrasInterface(GlInterface gl) : base(gl.GetProcAddress, gl.ContextInfo)
  311. {
  312. }
  313. public delegate void GlDeleteVertexArrays(int count, int[] buffers);
  314. [GlMinVersionEntryPoint("glDeleteVertexArrays", 3,0)]
  315. [GlExtensionEntryPoint("glDeleteVertexArraysOES", "GL_OES_vertex_array_object")]
  316. public GlDeleteVertexArrays DeleteVertexArrays { get; }
  317. public delegate void GlBindVertexArray(int array);
  318. [GlMinVersionEntryPoint("glBindVertexArray", 3,0)]
  319. [GlExtensionEntryPoint("glBindVertexArrayOES", "GL_OES_vertex_array_object")]
  320. public GlBindVertexArray BindVertexArray { get; }
  321. public delegate void GlGenVertexArrays(int n, int[] rv);
  322. [GlMinVersionEntryPoint("glGenVertexArrays",3,0)]
  323. [GlExtensionEntryPoint("glGenVertexArraysOES", "GL_OES_vertex_array_object")]
  324. public GlGenVertexArrays GenVertexArrays { get; }
  325. public int GenVertexArray()
  326. {
  327. var rv = new int[1];
  328. GenVertexArrays(1, rv);
  329. return rv[0];
  330. }
  331. }
  332. }
  333. }