Avalonia学习(二十八)-OpenGL

Avalonia已经继承了opengl,详细的大家可以自己查阅。Avalonia里面启用opengl继承OpenGlControlBase类就可以了。有三个方法。分别是初始化、绘制、释放。

这里把官方源码的例子扒出来给大家看一下。源码在我以前发布的单组件里面。地址在前面的界面总结博文里面。

关键源码:

    public class OpenGlPageControl : OpenGlControlBase{private float _yaw;public static readonly DirectProperty<OpenGlPageControl, float> YawProperty =AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Yaw", o => o.Yaw, (o, v) => o.Yaw = v);public float Yaw{get => _yaw;set => SetAndRaise(YawProperty, ref _yaw, value);}private float _pitch;public static readonly DirectProperty<OpenGlPageControl, float> PitchProperty =AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Pitch", o => o.Pitch, (o, v) => o.Pitch = v);public float Pitch{get => _pitch;set => SetAndRaise(PitchProperty, ref _pitch, value);}private float _roll;public static readonly DirectProperty<OpenGlPageControl, float> RollProperty =AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Roll", o => o.Roll, (o, v) => o.Roll = v);public float Roll{get => _roll;set => SetAndRaise(RollProperty, ref _roll, value);}private float _disco;public static readonly DirectProperty<OpenGlPageControl, float> DiscoProperty =AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Disco", o => o.Disco, (o, v) => o.Disco = v);public float Disco{get => _disco;set => SetAndRaise(DiscoProperty, ref _disco, value);}private string _info = string.Empty;public static readonly DirectProperty<OpenGlPageControl, string> InfoProperty =AvaloniaProperty.RegisterDirect<OpenGlPageControl, string>("Info", o => o.Info, (o, v) => o.Info = v);public string Info{get => _info;private set => SetAndRaise(InfoProperty, ref _info, value);}private int _vertexShader;private int _fragmentShader;private int _shaderProgram;private int _vertexBufferObject;private int _indexBufferObject;private int _vertexArrayObject;private string GetShader(bool fragment, string shader){var version = GlVersion.Type == GlProfileType.OpenGL ?RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 150 : 120 :100;var data = "#version " + version + "\n";if (GlVersion.Type == GlProfileType.OpenGLES)data += "precision mediump float;\n";if (version >= 150){shader = shader.Replace("attribute", "in");if (fragment)shader = shader.Replace("varying", "in").Replace("//DECLAREGLFRAG", "out vec4 outFragColor;").Replace("gl_FragColor", "outFragColor");elseshader = shader.Replace("varying", "out");}data += shader;return data;}private string VertexShaderSource => GetShader(false, @"attribute vec3 aPos;attribute vec3 aNormal;uniform mat4 uModel;uniform mat4 uProjection;uniform mat4 uView;varying vec3 FragPos;varying vec3 VecPos;  varying vec3 Normal;uniform float uTime;uniform float uDisco;void main(){float discoScale = sin(uTime * 10.0) / 10.0;float distortionX = 1.0 + uDisco * cos(uTime * 20.0) / 10.0;float scale = 1.0 + uDisco * discoScale;vec3 scaledPos = aPos;scaledPos.x = scaledPos.x * distortionX;scaledPos *= scale;gl_Position = uProjection * uView * uModel * vec4(scaledPos, 1.0);FragPos = vec3(uModel * vec4(aPos, 1.0));VecPos = aPos;Normal = normalize(vec3(uModel * vec4(aNormal, 1.0)));}
");private string FragmentShaderSource => GetShader(true, @"varying vec3 FragPos; varying vec3 VecPos; varying vec3 Normal;uniform float uMaxY;uniform float uMinY;uniform float uTime;uniform float uDisco;//DECLAREGLFRAGvoid main(){float y = (VecPos.y - uMinY) / (uMaxY - uMinY);float c = cos(atan(VecPos.x, VecPos.z) * 20.0 + uTime * 40.0 + y * 50.0);float s = sin(-atan(VecPos.z, VecPos.x) * 20.0 - uTime * 20.0 - y * 30.0);vec3 discoColor = vec3(0.5 + abs(0.5 - y) * cos(uTime * 10.0),0.25 + (smoothstep(0.3, 0.8, y) * (0.5 - c / 4.0)),0.25 + abs((smoothstep(0.1, 0.4, y) * (0.5 - s / 4.0))));vec3 objectColor = vec3((1.0 - y), 0.40 +  y / 4.0, y * 0.75 + 0.25);objectColor = objectColor * (1.0 - uDisco) + discoColor * uDisco;float ambientStrength = 0.3;vec3 lightColor = vec3(1.0, 1.0, 1.0);vec3 lightPos = vec3(uMaxY * 2.0, uMaxY * 2.0, uMaxY * 2.0);vec3 ambient = ambientStrength * lightColor;vec3 norm = normalize(Normal);vec3 lightDir = normalize(lightPos - FragPos);  float diff = max(dot(norm, lightDir), 0.0);vec3 diffuse = diff * lightColor;vec3 result = (ambient + diffuse) * objectColor;gl_FragColor = vec4(result, 1.0);}
");[StructLayout(LayoutKind.Sequential, Pack = 4)]private struct Vertex{public Vector3 Position;public Vector3 Normal;}private readonly Vertex[] _points;private readonly ushort[] _indices;private readonly float _minY;private readonly float _maxY;public OpenGlPageControl(){var name = typeof(OpenGlPage).Assembly.GetManifestResourceNames().First(x => x.Contains("teapot.bin"));using (var sr = new BinaryReader(typeof(OpenGlPage).Assembly.GetManifestResourceStream(name)!)){var buf = new byte[sr.ReadInt32()];sr.Read(buf, 0, buf.Length);var points = new float[buf.Length / 4];Buffer.BlockCopy(buf, 0, points, 0, buf.Length);buf = new byte[sr.ReadInt32()];sr.Read(buf, 0, buf.Length);_indices = new ushort[buf.Length / 2];Buffer.BlockCopy(buf, 0, _indices, 0, buf.Length);_points = new Vertex[points.Length / 3];for (var primitive = 0; primitive < points.Length / 3; primitive++){var srci = primitive * 3;_points[primitive] = new Vertex{Position = new Vector3(points[srci], points[srci + 1], points[srci + 2])};}for (int i = 0; i < _indices.Length; i += 3){Vector3 a = _points[_indices[i]].Position;Vector3 b = _points[_indices[i + 1]].Position;Vector3 c = _points[_indices[i + 2]].Position;var normal = Vector3.Normalize(Vector3.Cross(c - b, a - b));_points[_indices[i]].Normal += normal;_points[_indices[i + 1]].Normal += normal;_points[_indices[i + 2]].Normal += normal;}for (int i = 0; i < _points.Length; i++){_points[i].Normal = Vector3.Normalize(_points[i].Normal);_maxY = Math.Max(_maxY, _points[i].Position.Y);_minY = Math.Min(_minY, _points[i].Position.Y);}}}private static void CheckError(GlInterface gl){int err;while ((err = gl.GetError()) != GlConsts.GL_NO_ERROR)Console.WriteLine(err);}protected override unsafe void OnOpenGlInit(GlInterface GL){CheckError(GL);Info = $"Renderer: {GL.GetString(GlConsts.GL_RENDERER)} Version: {GL.GetString(GlConsts.GL_VERSION)}";// Load the source of the vertex shader and compile it._vertexShader = GL.CreateShader(GlConsts.GL_VERTEX_SHADER);Console.WriteLine(GL.CompileShaderAndGetError(_vertexShader, VertexShaderSource));// Load the source of the fragment shader and compile it._fragmentShader = GL.CreateShader(GlConsts.GL_FRAGMENT_SHADER);Console.WriteLine(GL.CompileShaderAndGetError(_fragmentShader, FragmentShaderSource));// Create the shader program, attach the vertex and fragment shaders and link the program._shaderProgram = GL.CreateProgram();GL.AttachShader(_shaderProgram, _vertexShader);GL.AttachShader(_shaderProgram, _fragmentShader);const int positionLocation = 0;const int normalLocation = 1;GL.BindAttribLocationString(_shaderProgram, positionLocation, "aPos");GL.BindAttribLocationString(_shaderProgram, normalLocation, "aNormal");Console.WriteLine(GL.LinkProgramAndGetError(_shaderProgram));CheckError(GL);// Create the vertex buffer object (VBO) for the vertex data._vertexBufferObject = GL.GenBuffer();// Bind the VBO and copy the vertex data into it.GL.BindBuffer(GlConsts.GL_ARRAY_BUFFER, _vertexBufferObject);CheckError(GL);var vertexSize = Marshal.SizeOf<Vertex>();fixed (void* pdata = _points)GL.BufferData(GlConsts.GL_ARRAY_BUFFER, new nint(_points.Length * vertexSize),new nint(pdata), GlConsts.GL_STATIC_DRAW);_indexBufferObject = GL.GenBuffer();GL.BindBuffer(GlConsts.GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);CheckError(GL);fixed (void* pdata = _indices)GL.BufferData(GlConsts.GL_ELEMENT_ARRAY_BUFFER, new nint(_indices.Length * sizeof(ushort)), new nint(pdata),GlConsts.GL_STATIC_DRAW);CheckError(GL);_vertexArrayObject = GL.GenVertexArray();GL.BindVertexArray(_vertexArrayObject);CheckError(GL);GL.VertexAttribPointer(positionLocation, 3, GlConsts.GL_FLOAT,0, vertexSize, nint.Zero);GL.VertexAttribPointer(normalLocation, 3, GlConsts.GL_FLOAT,0, vertexSize, new nint(12));GL.EnableVertexAttribArray(positionLocation);GL.EnableVertexAttribArray(normalLocation);CheckError(GL);}protected override void OnOpenGlDeinit(GlInterface GL){// Unbind everythingGL.BindBuffer(GlConsts.GL_ARRAY_BUFFER, 0);GL.BindBuffer(GlConsts.GL_ELEMENT_ARRAY_BUFFER, 0);GL.BindVertexArray(0);GL.UseProgram(0);// Delete all resources.GL.DeleteBuffer(_vertexBufferObject);GL.DeleteBuffer(_indexBufferObject);GL.DeleteVertexArray(_vertexArrayObject);GL.DeleteProgram(_shaderProgram);GL.DeleteShader(_fragmentShader);GL.DeleteShader(_vertexShader);}static Stopwatch St = Stopwatch.StartNew();protected override unsafe void OnOpenGlRender(GlInterface gl, int fb){gl.ClearColor(0, 0, 0, 0);gl.Clear(GlConsts.GL_COLOR_BUFFER_BIT | GlConsts.GL_DEPTH_BUFFER_BIT);gl.Enable(GlConsts.GL_DEPTH_TEST);gl.Viewport(0, 0, (int)Bounds.Width, (int)Bounds.Height);var GL = gl;GL.BindBuffer(GlConsts.GL_ARRAY_BUFFER, _vertexBufferObject);GL.BindBuffer(GlConsts.GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);GL.BindVertexArray(_vertexArrayObject);GL.UseProgram(_shaderProgram);CheckError(GL);var projection =Matrix4x4.CreatePerspectiveFieldOfView((float)(Math.PI / 4), (float)(Bounds.Width / Bounds.Height),0.01f, 1000);var view = Matrix4x4.CreateLookAt(new Vector3(25, 25, 25), new Vector3(), new Vector3(0, 1, 0));var model = Matrix4x4.CreateFromYawPitchRoll(_yaw, _pitch, _roll);var modelLoc = GL.GetUniformLocationString(_shaderProgram, "uModel");var viewLoc = GL.GetUniformLocationString(_shaderProgram, "uView");var projectionLoc = GL.GetUniformLocationString(_shaderProgram, "uProjection");var maxYLoc = GL.GetUniformLocationString(_shaderProgram, "uMaxY");var minYLoc = GL.GetUniformLocationString(_shaderProgram, "uMinY");var timeLoc = GL.GetUniformLocationString(_shaderProgram, "uTime");var discoLoc = GL.GetUniformLocationString(_shaderProgram, "uDisco");GL.UniformMatrix4fv(modelLoc, 1, false, &model);GL.UniformMatrix4fv(viewLoc, 1, false, &view);GL.UniformMatrix4fv(projectionLoc, 1, false, &projection);GL.Uniform1f(maxYLoc, _maxY);GL.Uniform1f(minYLoc, _minY);GL.Uniform1f(timeLoc, (float)St.Elapsed.TotalSeconds);GL.Uniform1f(discoLoc, _disco);CheckError(GL);GL.DrawElements(GlConsts.GL_TRIANGLES, _indices.Length, GlConsts.GL_UNSIGNED_SHORT, nint.Zero);CheckError(GL);if (_disco > 0.01)RequestNextFrameRendering();}protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change){if (change.Property == YawProperty || change.Property == RollProperty || change.Property == PitchProperty ||change.Property == DiscoProperty)RequestNextFrameRendering();base.OnPropertyChanged(change);}}

另外还需要一个teapot.bin文件,嵌入方式。你如果想运行,还得下载源码或者下载我得代码。

运行效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/714811.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

YOLOv9有效改进|使用空间和通道重建卷积SCConv改进RepNCSPELAN4

专栏介绍&#xff1a;YOLOv9改进系列 | 包含深度学习最新创新&#xff0c;主力高效涨点&#xff01;&#xff01;&#xff01; 一、改进点介绍 SCConv是一种即插即用的空间和通道重建卷积。 RepNCSPELAN4是YOLOv9中的特征提取模块&#xff0c;类似YOLOv5和v8中的C2f与C3模块。 …

MySQL进阶:MySQL事务、并发事务问题及隔离级别

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位大四、研0学生&#xff0c;正在努力准备大四暑假的实习、 &#x1f30c;上期文章&#xff1a;MySQL进阶&#xff1a;视图&&存储过程&&存储函数&&触发器 &#x1f4da;订阅专栏&#xff1a;MySQL进…

Docker Machine windows系统下 安装

如果你是 Windows 平台&#xff0c;可以使用 Git BASH&#xff0c;并输入以下命令&#xff1a; basehttps://github.com/docker/machine/releases/download/v0.16.0 &&mkdir -p "$HOME/bin" &&curl -L $base/docker-machine-Windows-x86_64.exe >…

点燃技能火花:探索PyTorch学习网站,开启AI编程之旅!

介绍&#xff1a;PyTorch是一个开源的Python机器学习库&#xff0c;它基于Torch&#xff0c;专为深度学习和科学计算而设计&#xff0c;特别适合于自然语言处理等应用程序。以下是对PyTorch的详细介绍&#xff1a; 历史背景&#xff1a;PyTorch起源于Torch&#xff0c;一个用于…

【真机Bug】异步加载资源未完成访问单例导致资源创建失败

1.错误表现描述 抽卡时&#xff0c;10抽展示界面为A。抽取内容可能是整卡或者碎片&#xff0c;抽到整卡&#xff0c;会有立绘展示和点击详情的按钮。点击详情后出现详情页B。【此时界面A预制体被销毁&#xff0c;卡片数据进入数据缓存池】点击页面B的返回按钮&#xff0c;单例…

C++——模版

前言&#xff1a;哈喽小伙伴们好久不见&#xff0c;这是2024年的第一篇博文&#xff0c;我们将继续C的学习&#xff0c;今天这篇文章&#xff0c;我们来习一下——模版。 目录 一.什么是模版 二.模版分类 1.函数模版 2.类模板 总结 一.什么是模版 说起模版&#xff0c;我们…

高性能通信之Netty

一, 同步IO(BIO)模型的架构 一般针对性能不高的情况下可以使用. 二,异步IO(NIO)模型的架构 多路复用(epoll模型):

【LeetCode:124. 二叉树中的最大路径和 + 二叉树+递归】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

【力扣hot100】刷题笔记Day19

前言 回溯回溯回溯&#xff01;早上整理档案竟然用了桶排序&#xff0c;不愧是算法狂魔们 79. 单词搜索 - 力扣&#xff08;LeetCode&#xff09; DFS class Solution:def exist(self, board: List[List[str]], word: str) -> bool:m, n len(board), len(board[0])# used…

谈谈高并发系统的设计方法论

谈谈高并发系统的设计方法论 何为高并发系统&#xff1f;什么是并发&#xff08;Conurrent&#xff09;&#xff1f;什么是高并发&#xff08;Hight Concurrnet&#xff09;&#xff1f;高并发的衡量指标有哪些&#xff1f; 实现高并发系统的两大板块高并发系统应用程序侧的设计…

腾讯云学生服务器使用教程_申请腾讯云学生机详细流程

2024年腾讯云学生服务器优惠活动「云校园」&#xff0c;学生服务器优惠价格&#xff1a;轻量应用服务器2核2G学生价30元3个月、58元6个月、112元一年&#xff0c;轻量应用服务器4核8G配置191.1元3个月、352.8元6个月、646.8元一年&#xff0c;CVM云服务器2核4G配置842.4元一年&…

还在用Jenkins?快来试试这款简而轻的自动部署软件!

最近发现了一个比 Jenkins 使用更简单的项目构建和部署工具&#xff0c;完全可以满足个人以及一些小企业的需求&#xff0c;分享一下。 Jpom 是一款 Java 开发的简单轻量的低侵入式在线构建、自动部署、日常运维、项目监控软件。 日常开发中&#xff0c;Jpom 可以解决下面这些…

吴恩达机器学习全课程笔记第五篇

目录 前言 P80-P85 添加数据 迁移学习 机器学习项目的完整周期 公平、偏见与伦理 P86-P95 倾斜数据集的误差指标 决策树模型 测量纯度 选择拆分方式增益 使用分类特征的一种独热编码 连续的有价值特征 回归树 前言 这是吴恩达机器学习笔记的第五篇&#xff0c…

《2023跨境电商投诉大数据报告》发布|亚马逊 天猫国际 考拉海购 敦煌网 阿里巴巴

2023年&#xff0c;跨境电商API接口天猫国际、京东国际和抖音全球购以其强大的品牌影响力和市场占有率&#xff0c;稳坐行业前三的位置。同时&#xff0c;各大跨境电商平台消费纠纷问题层出不穷。依据国内知名网络消费纠纷调解平台“电诉宝”&#xff08;315.100EC.CN&#xff…

javaEE--后端环境变量配置

目录 pre 文件准备 最终运行成功结果 后端运行步骤 1.修改setenv文件 2.运行setenv&#xff0c;设置环境变量 3.查看jdk版本 4.修改mysql文件夹下的my文件 前端运行步骤 1.nodejs环境配置 2.查看node和npm版本 3.下载并运行npm 4.注册登录 pre 文件准备 最终运行…

VR转接器:破解虚拟与现实边界的革命性设备

VR转接器&#xff0c;这一革命性的设备&#xff0c;为虚拟现实体验带来了前所未有的自由度。它巧妙地连接了虚拟与现实&#xff0c;使得用户在享受VR眼镜带来的奇幻世界的同时&#xff0c;也能自由地在现实世界中活动。这一设计的诞生&#xff0c;不仅解决了VR眼镜续航的瓶颈问…

GO结构体

1. 结构体 Go语言可以通过自定义的方式形成新的类型&#xff0c;结构体就是这些类型中的一种复合类型&#xff0c;结构体是由零个或多个任意类型的值聚合成的实体&#xff0c;每个值都可以称为结构体的成员。 结构体成员也可以称为“字段”&#xff0c;这些字段有以下特性&am…

STM32 | 零基础 STM32 第一天

零基础 STM32 第一天 一、认知STM32 1、STM32概念 STM32:意法半导体基于ARM公司的Cortex-M内核开发的32位的高性能、低功耗单片机。 ST:意法半导体 M:基于ARM公司的Cortex-M内核的高性能、低功耗单片机 32&#xff1a;32位单片机 2、STM32开发的产品 STM32开发的产品&a…

【论文笔记】Improving Language Understanding by Generative Pre-Training

Improving Language Understanding by Generative Pre-Training 文章目录 Improving Language Understanding by Generative Pre-TrainingAbstract1 Introduction2 Related WorkSemi-supervised learning for NLPUnsupervised pre-trainingAuxiliary training objectives 3 Fra…

Java 网络面试题解析

1. Http 协议的状态码有哪些&#xff1f;含义是什么&#xff1f;【重点】 200&#xff1a;OK&#xff0c;客户端请求成功。 301&#xff1a;Moved Permanently&#xff08;永久移除&#xff09;&#xff0c;请求的URL已移走。Response中应该包含一个Location URL&#xff0c;…