OpenGlPage.xaml.cs 14 KB

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