OpenGlPage.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 = string.Empty;
  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. private int _vertexShader;
  63. private int _fragmentShader;
  64. private int _shaderProgram;
  65. private int _vertexBufferObject;
  66. private int _indexBufferObject;
  67. private int _vertexArrayObject;
  68. private string GetShader(bool fragment, string shader)
  69. {
  70. var version = (GlVersion.Type == GlProfileType.OpenGL ?
  71. RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 150 : 120 :
  72. 100);
  73. var data = "#version " + version + "\n";
  74. if (GlVersion.Type == GlProfileType.OpenGLES)
  75. data += "precision mediump float;\n";
  76. if (version >= 150)
  77. {
  78. shader = shader.Replace("attribute", "in");
  79. if (fragment)
  80. shader = shader
  81. .Replace("varying", "in")
  82. .Replace("//DECLAREGLFRAG", "out vec4 outFragColor;")
  83. .Replace("gl_FragColor", "outFragColor");
  84. else
  85. shader = shader.Replace("varying", "out");
  86. }
  87. data += shader;
  88. return data;
  89. }
  90. private string VertexShaderSource => GetShader(false, @"
  91. attribute vec3 aPos;
  92. attribute vec3 aNormal;
  93. uniform mat4 uModel;
  94. uniform mat4 uProjection;
  95. uniform mat4 uView;
  96. varying vec3 FragPos;
  97. varying vec3 VecPos;
  98. varying vec3 Normal;
  99. uniform float uTime;
  100. uniform float uDisco;
  101. void main()
  102. {
  103. float discoScale = sin(uTime * 10.0) / 10.0;
  104. float distortionX = 1.0 + uDisco * cos(uTime * 20.0) / 10.0;
  105. float scale = 1.0 + uDisco * discoScale;
  106. vec3 scaledPos = aPos;
  107. scaledPos.x = scaledPos.x * distortionX;
  108. scaledPos *= scale;
  109. gl_Position = uProjection * uView * uModel * vec4(scaledPos, 1.0);
  110. FragPos = vec3(uModel * vec4(aPos, 1.0));
  111. VecPos = aPos;
  112. Normal = normalize(vec3(uModel * vec4(aNormal, 1.0)));
  113. }
  114. ");
  115. private string FragmentShaderSource => GetShader(true, @"
  116. varying vec3 FragPos;
  117. varying vec3 VecPos;
  118. varying vec3 Normal;
  119. uniform float uMaxY;
  120. uniform float uMinY;
  121. uniform float uTime;
  122. uniform float uDisco;
  123. //DECLAREGLFRAG
  124. void main()
  125. {
  126. float y = (VecPos.y - uMinY) / (uMaxY - uMinY);
  127. float c = cos(atan(VecPos.x, VecPos.z) * 20.0 + uTime * 40.0 + y * 50.0);
  128. float s = sin(-atan(VecPos.z, VecPos.x) * 20.0 - uTime * 20.0 - y * 30.0);
  129. vec3 discoColor = vec3(
  130. 0.5 + abs(0.5 - y) * cos(uTime * 10.0),
  131. 0.25 + (smoothstep(0.3, 0.8, y) * (0.5 - c / 4.0)),
  132. 0.25 + abs((smoothstep(0.1, 0.4, y) * (0.5 - s / 4.0))));
  133. vec3 objectColor = vec3((1.0 - y), 0.40 + y / 4.0, y * 0.75 + 0.25);
  134. objectColor = objectColor * (1.0 - uDisco) + discoColor * uDisco;
  135. float ambientStrength = 0.3;
  136. vec3 lightColor = vec3(1.0, 1.0, 1.0);
  137. vec3 lightPos = vec3(uMaxY * 2.0, uMaxY * 2.0, uMaxY * 2.0);
  138. vec3 ambient = ambientStrength * lightColor;
  139. vec3 norm = normalize(Normal);
  140. vec3 lightDir = normalize(lightPos - FragPos);
  141. float diff = max(dot(norm, lightDir), 0.0);
  142. vec3 diffuse = diff * lightColor;
  143. vec3 result = (ambient + diffuse) * objectColor;
  144. gl_FragColor = vec4(result, 1.0);
  145. }
  146. ");
  147. [StructLayout(LayoutKind.Sequential, Pack = 4)]
  148. private struct Vertex
  149. {
  150. public Vector3 Position;
  151. public Vector3 Normal;
  152. }
  153. private readonly Vertex[] _points;
  154. private readonly ushort[] _indices;
  155. private readonly float _minY;
  156. private readonly float _maxY;
  157. public OpenGlPageControl()
  158. {
  159. var name = typeof(OpenGlPage).Assembly.GetManifestResourceNames().First(x => x.Contains("teapot.bin"));
  160. using (var sr = new BinaryReader(typeof(OpenGlPage).Assembly.GetManifestResourceStream(name)!))
  161. {
  162. var buf = new byte[sr.ReadInt32()];
  163. sr.Read(buf, 0, buf.Length);
  164. var points = new float[buf.Length / 4];
  165. Buffer.BlockCopy(buf, 0, points, 0, buf.Length);
  166. buf = new byte[sr.ReadInt32()];
  167. sr.Read(buf, 0, buf.Length);
  168. _indices = new ushort[buf.Length / 2];
  169. Buffer.BlockCopy(buf, 0, _indices, 0, buf.Length);
  170. _points = new Vertex[points.Length / 3];
  171. for (var primitive = 0; primitive < points.Length / 3; primitive++)
  172. {
  173. var srci = primitive * 3;
  174. _points[primitive] = new Vertex
  175. {
  176. Position = new Vector3(points[srci], points[srci + 1], points[srci + 2])
  177. };
  178. }
  179. for (int i = 0; i < _indices.Length; i += 3)
  180. {
  181. Vector3 a = _points[_indices[i]].Position;
  182. Vector3 b = _points[_indices[i + 1]].Position;
  183. Vector3 c = _points[_indices[i + 2]].Position;
  184. var normal = Vector3.Normalize(Vector3.Cross(c - b, a - b));
  185. _points[_indices[i]].Normal += normal;
  186. _points[_indices[i + 1]].Normal += normal;
  187. _points[_indices[i + 2]].Normal += normal;
  188. }
  189. for (int i = 0; i < _points.Length; i++)
  190. {
  191. _points[i].Normal = Vector3.Normalize(_points[i].Normal);
  192. _maxY = Math.Max(_maxY, _points[i].Position.Y);
  193. _minY = Math.Min(_minY, _points[i].Position.Y);
  194. }
  195. }
  196. }
  197. private static void CheckError(GlInterface gl)
  198. {
  199. int err;
  200. while ((err = gl.GetError()) != GL_NO_ERROR)
  201. Console.WriteLine(err);
  202. }
  203. protected override unsafe void OnOpenGlInit(GlInterface GL)
  204. {
  205. CheckError(GL);
  206. Info = $"Renderer: {GL.GetString(GL_RENDERER)} Version: {GL.GetString(GL_VERSION)}";
  207. // Load the source of the vertex shader and compile it.
  208. _vertexShader = GL.CreateShader(GL_VERTEX_SHADER);
  209. Console.WriteLine(GL.CompileShaderAndGetError(_vertexShader, VertexShaderSource));
  210. // Load the source of the fragment shader and compile it.
  211. _fragmentShader = GL.CreateShader(GL_FRAGMENT_SHADER);
  212. Console.WriteLine(GL.CompileShaderAndGetError(_fragmentShader, FragmentShaderSource));
  213. // Create the shader program, attach the vertex and fragment shaders and link the program.
  214. _shaderProgram = GL.CreateProgram();
  215. GL.AttachShader(_shaderProgram, _vertexShader);
  216. GL.AttachShader(_shaderProgram, _fragmentShader);
  217. const int positionLocation = 0;
  218. const int normalLocation = 1;
  219. GL.BindAttribLocationString(_shaderProgram, positionLocation, "aPos");
  220. GL.BindAttribLocationString(_shaderProgram, normalLocation, "aNormal");
  221. Console.WriteLine(GL.LinkProgramAndGetError(_shaderProgram));
  222. CheckError(GL);
  223. // Create the vertex buffer object (VBO) for the vertex data.
  224. _vertexBufferObject = GL.GenBuffer();
  225. // Bind the VBO and copy the vertex data into it.
  226. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  227. CheckError(GL);
  228. var vertexSize = Marshal.SizeOf<Vertex>();
  229. fixed (void* pdata = _points)
  230. GL.BufferData(GL_ARRAY_BUFFER, new IntPtr(_points.Length * vertexSize),
  231. new IntPtr(pdata), GL_STATIC_DRAW);
  232. _indexBufferObject = GL.GenBuffer();
  233. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  234. CheckError(GL);
  235. fixed (void* pdata = _indices)
  236. GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, new IntPtr(_indices.Length * sizeof(ushort)), new IntPtr(pdata),
  237. GL_STATIC_DRAW);
  238. CheckError(GL);
  239. _vertexArrayObject = GL.GenVertexArray();
  240. GL.BindVertexArray(_vertexArrayObject);
  241. CheckError(GL);
  242. GL.VertexAttribPointer(positionLocation, 3, GL_FLOAT,
  243. 0, vertexSize, IntPtr.Zero);
  244. GL.VertexAttribPointer(normalLocation, 3, GL_FLOAT,
  245. 0, vertexSize, new IntPtr(12));
  246. GL.EnableVertexAttribArray(positionLocation);
  247. GL.EnableVertexAttribArray(normalLocation);
  248. CheckError(GL);
  249. }
  250. protected override void OnOpenGlDeinit(GlInterface GL)
  251. {
  252. // Unbind everything
  253. GL.BindBuffer(GL_ARRAY_BUFFER, 0);
  254. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  255. GL.BindVertexArray(0);
  256. GL.UseProgram(0);
  257. // Delete all resources.
  258. GL.DeleteBuffer(_vertexBufferObject);
  259. GL.DeleteBuffer(_indexBufferObject);
  260. GL.DeleteVertexArray(_vertexArrayObject);
  261. GL.DeleteProgram(_shaderProgram);
  262. GL.DeleteShader(_fragmentShader);
  263. GL.DeleteShader(_vertexShader);
  264. }
  265. static Stopwatch St = Stopwatch.StartNew();
  266. protected override unsafe void OnOpenGlRender(GlInterface gl, int fb)
  267. {
  268. gl.ClearColor(0, 0, 0, 0);
  269. gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  270. gl.Enable(GL_DEPTH_TEST);
  271. gl.Viewport(0, 0, (int)Bounds.Width, (int)Bounds.Height);
  272. var GL = gl;
  273. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  274. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  275. GL.BindVertexArray(_vertexArrayObject);
  276. GL.UseProgram(_shaderProgram);
  277. CheckError(GL);
  278. var projection =
  279. Matrix4x4.CreatePerspectiveFieldOfView((float)(Math.PI / 4), (float)(Bounds.Width / Bounds.Height),
  280. 0.01f, 1000);
  281. var view = Matrix4x4.CreateLookAt(new Vector3(25, 25, 25), new Vector3(), new Vector3(0, 1, 0));
  282. var model = Matrix4x4.CreateFromYawPitchRoll(_yaw, _pitch, _roll);
  283. var modelLoc = GL.GetUniformLocationString(_shaderProgram, "uModel");
  284. var viewLoc = GL.GetUniformLocationString(_shaderProgram, "uView");
  285. var projectionLoc = GL.GetUniformLocationString(_shaderProgram, "uProjection");
  286. var maxYLoc = GL.GetUniformLocationString(_shaderProgram, "uMaxY");
  287. var minYLoc = GL.GetUniformLocationString(_shaderProgram, "uMinY");
  288. var timeLoc = GL.GetUniformLocationString(_shaderProgram, "uTime");
  289. var discoLoc = GL.GetUniformLocationString(_shaderProgram, "uDisco");
  290. GL.UniformMatrix4fv(modelLoc, 1, false, &model);
  291. GL.UniformMatrix4fv(viewLoc, 1, false, &view);
  292. GL.UniformMatrix4fv(projectionLoc, 1, false, &projection);
  293. GL.Uniform1f(maxYLoc, _maxY);
  294. GL.Uniform1f(minYLoc, _minY);
  295. GL.Uniform1f(timeLoc, (float)St.Elapsed.TotalSeconds);
  296. GL.Uniform1f(discoLoc, _disco);
  297. CheckError(GL);
  298. GL.DrawElements(GL_TRIANGLES, _indices.Length, GL_UNSIGNED_SHORT, IntPtr.Zero);
  299. CheckError(GL);
  300. if (_disco > 0.01)
  301. RequestNextFrameRendering();
  302. }
  303. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  304. {
  305. if (change.Property == YawProperty || change.Property == RollProperty || change.Property == PitchProperty ||
  306. change.Property == DiscoProperty)
  307. RequestNextFrameRendering();
  308. base.OnPropertyChanged(change);
  309. }
  310. }
  311. }