[英]How to use fragment shader to draw sphere ilusion in OpenGL ES?
我正在使用此简单功能在面向相机的3D空间中绘制四边形。 现在,我想使用片段着色器在内部绘制一个球体的错觉。 但是,问题是我是OpenGL ES的新手,所以我不知道怎么办?
void draw_sphere(view_t view) {
set_gl_options(COURSE);
glPushMatrix();
{
glTranslatef(view.plyr_pos.x, view.plyr_pos.y, view.plyr_pos.z - 1.9);
#ifdef __APPLE__
#undef glEnableClientState
#undef glDisableClientState
#undef glVertexPointer
#undef glTexCoordPointer
#undef glDrawArrays
static const GLfloat vertices []=
{
0, 0, 0,
1, 0, 0,
1, 1, 0,
0, 1, 0,
0, 0, 0,
1, 1, 0
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
#else
#endif
}
glPopMatrix();
}
更确切地说,我想实现以下目标:
要实现此目标,可能需要做很多事情...在您发布的最后一张图像上绘制的球体是使用照明,光泽和颜色的结果。 通常,您需要一个可以处理所有内容并且通常可以适用于任何形状的着色器。
可以用单个四边形绘制此特定情况(也可以用数学方式表示其他一些情况),而无需将法向坐标推送到程序。 您需要做的是在片段着色器中创建一个法线:如果接收到向量sphereCenter
, fragmentPosition
和float sphereRadius
,那么sphereNormal
是一个向量,例如
sphereNormal = (fragmentPosition-sphereCenter)/radius; //taking into account all have .z = .0
sphereNormal.z = -sqrt(1.0 - length(sphereNormal)); //only if(length(spherePosition) < sphereRadius)
和实际球体位置:
spherePosition = sphereCenter + sphereNormal*sphereRadius;
现在,您需要做的就是添加照明。静态或非静态最常见的是使用一些环境因素,线性和平方距离因素,发光因素:
color = ambient*materialColor; //apply ambient
vector fragmentToLight = lightPosition-spherePosition;
float lightDistance = length(fragmentToLight);
fragmentToLight = normalize(fragmentToLight); //can also just divide with light distance
float dotFactor = dot(sphereNormal, fragmentToLight); //dot factor is used to take int account the angle between light and surface normal
if(dotFactor > .0) {
color += (materialColor*dotFactor)/(1.0 + lightDistance*linearFactor + lightDistance*lightDistance*squareFactor); //apply dot factor and distance factors (in many cases the distance factors are 0)
}
vector shineVector = (sphereNormal*(2.0*dotFactor)) - fragmentToLight; //this is a vector that is mirrored through the normal, it is a reflection vector
float shineFactor = dot(shineVector, normalize(cameraPosition-spherePosition)); //factor represents how strong is the light reflection towards the viewer
if(shineFactor > .0) {
color += materialColor*(shineFactor*shineFactor * shine); //or some other power then 2 (shineFactor*shineFactor)
}
在片段着色器中创建光的这种模式是很多模式之一。 如果您不喜欢它或无法使其正常运行,我建议您在网络上找到另一个,否则,我希望您能理解并能够试用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.