因为前两周一直在寻找处理VR反畸变的方法,发现了这个工具,它是一个调试渲染很棒的工具,直接在线输入代码,即时显示你的渲染效果,一直没来得及记录下来,畸变已经处理差不多了,现在来把这个工具的处理畸变的方法记录下来. ShaderToy是一个计算机图形方面的在线的学习,交流平台.在这个平台上使用GLSL语言(语法跟C很像,如果你学习过C语言,操作它基本没什么问题)就能画出很漂亮的渲染效果.你可以在官网上看到人分享的链接(包含源码). 这里分享两个ShaderToy上调试可能需要的链接:
GLSL4.5的语法规范ShaderToy使用教程(我最初也是看这个教程,来学习的)至于为什么会产生畸变?畸变是什么?如果修正畸变?这些问题查看之前发的几篇关于畸变的文章吧. 这里直接上反畸变主要算法:
//这里假设畸变中心的坐标是(0.5,0.5).//计算的公式来自这个视频:https://www.youtube.com/watch?v=B7qrgrrHry0&feature=youtu.be和Wikipedia的畸变校正算法:https://en.wikipedia.org/wiki/Distortion_(optics)#Software_correctionrr = sqrt((fU - 0.5f)*(fU - 0.5f) + (fV - 0.5f)*(fV - 0.5f));r2 = rr * (1 + K1*(rr*rr) + K2*(rr*rr*rr*rr));theta = atan2(fU-0.5f, fV-0.5f);//图像经过畸变后会明显的变小,需要在这里乘以放大系数,来充满整个屏幕.hX = sin(theta)*r2*1.0;hY = cos(theta)*r2*1.0;渲染效果,已经上传ShaderToy上:barrel&pincushion distortion 代码如下:
void mainImage( out vec4 fragColor, in vec2 fragCoord ) { //If you have any questions, you can send me Email:helenhololens@Gmail.com //get source_uv vec2 source_uv = fragCoord.xy / iResolution.xy; //assume your distortion center coordinate is (0.5,0.5),you can use your distortion center instead. vec2 distortion_center = vec2(0.5,0.5); //Define algorithm dependent variables float distortion_x,distortion_y,rr,r2,theta; //define distortion coefficient K1 and K2 ,In most cases we can only adjust K1. then K2 parameters can be adjusted more perfect Effect //iGlobalTime is used for Real-time change. //K1 < 0 is pincushion distortion //K1 >=0 is barrel distortion float distortion_k1 = 1.0 * sin(iGlobalTime*0.5),distortion_k2 = 0.5; vec2 dest_uv; //--------------------------Algorithm Start---------------------------------------- //The formula is derived from this video:https://www.youtube.com/watch?v=B7qrgrrHry0&feature=youtu.be //and Distortion correction algorithm for Wikipedia:https://en.wikipedia.org/wiki/Distortion_(optics)#Software_correction rr = sqrt((source_uv.x - distortion_center.x)*(source_uv.x - distortion_center.x) + (source_uv.y - distortion_center.y)*(source_uv.y - distortion_center.y)); r2 = rr * (1.0 + distortion_k1*(rr*rr) + distortion_k2*(rr*rr*rr*rr)); theta = atan(source_uv.x - distortion_center.x, source_uv.y - distortion_center.y); distortion_x = sin(theta) * r2 * 1.0;//1.0 is scale factor distortion_y = cos(theta) * r2 * 1.0;//1.0 is scale factor dest_uv.x = distortion_x + 0.5; dest_uv.y = distortion_y + 0.5; //--------------------------Algorithm End------------------------------------------ //Get texture from Channel0,and set dest_uv. fragColor = vec4( texture( iChannel0, dest_uv).r, texture( iChannel0,dest_uv).g,texture( iChannel0,dest_uv).b, 1. );}上面的代码中畸变参数K1,K2是畸变调节的参数,想要效果好就根据畸变算法所示那样,叠加到Kn,多数情况下调整K1是能够满足需求的.”float distortion_k1 = 1.0 * sin(iGlobalTime*0.5)”这里的”iGlobalTime”是一个全局的时间变量,是为了让画面有动态效果,如果只想要做反畸变,可以把K1直接设置为0.5(这个值在项目中是要根据光学镜片的畸变来调整de,有一些辅助工具可以帮助获得这个值),就能看到”桶”型的反畸变效果: 原图如下:
代码其他部分,已经添加注释了,如果项目中需要用到反畸变,可以将上面的代码移植到自己所在的平台上,我这里在openVR上调试后,效果还是可以的.
PS:最后,ShaderToy这工具真的很棒,纯用数学算法就能制作出很精美的动画,如果开放纹理上传功能就更完美了.
新闻热点
疑难解答