如何在opengl中获得聚光灯?

时间:2012-11-21 13:10:08

标签: c++ opengl

参考 http://www.chai3d.org/doc/classc_light.html

    light2->setPos(cVector3d( 0, 0,0.0));  // position the light source
    light2->m_ambient.set(0.8, 0.8, 0.8);
    light2->m_diffuse.set(0.8, 0.8, 0.8);
    light2->m_specular.set(0.8, 0.8, 0.8);
    light2->setDirectionalLight(false);//make a positional light

使用opengl的渲染代码是

void cLight::renderLightSource()
{
    // check if light source enabled
    if (m_enabled == false)
    {
        // disable OpenGL light source
        glDisable(m_glLightNumber);
        return;
    }

    computeGlobalCurrentObjectOnly();

    // enable this light in OpenGL
    glEnable(m_glLightNumber);

    // set lighting components
    glLightfv(m_glLightNumber, GL_AMBIENT,  m_ambient.pColor());
    glLightfv(m_glLightNumber, GL_DIFFUSE,  m_diffuse.pColor() );
    glLightfv(m_glLightNumber, GL_SPECULAR, m_specular.pColor());

    // position the light source in (global) space (because we're not
    // _rendered_ as part of the scene graph)
    float position[4];

    position[0] = (float)m_globalPos.x;
    position[1] = (float)m_globalPos.y;
    position[2] = (float)m_globalPos.z;
    //position[0] = (float)m_localPos.x;
    //position[1] = (float)m_localPos.y;
    //position[2] = (float)m_localPos.z;

    // Directional light source...
    if (m_directionalLight) position[3] = 0.0f;

    // Positional light source...
    else position[3] = 1.0f;

    glLightfv(m_glLightNumber, GL_POSITION, (const float *)&position);

    // set cutoff angle
    glLightf(m_glLightNumber, GL_SPOT_CUTOFF, m_cutOffAngle);

    // set the direction of my light beam, if I'm a _positional_ spotlight
    if (m_directionalLight == false)
    {
        cVector3d dir = m_globalRot.getCol0();
        float direction[4];
        direction[0] = (float)dir.x;
        direction[1] = (float)dir.y;
        direction[2] = (float)dir.z;
        direction[3] = 0.0f;
        glLightfv(m_glLightNumber, GL_SPOT_DIRECTION, (const float *)&direction);
    }

    // set attenuation factors
    glLightf(m_glLightNumber, GL_CONSTANT_ATTENUATION, m_attConstant);
    glLightf(m_glLightNumber, GL_LINEAR_ATTENUATION, m_attLinear);
    glLightf(m_glLightNumber, GL_QUADRATIC_ATTENUATION, m_attQuadratic);

    // set exponent factor
    glLightf(m_glLightNumber, GL_SPOT_EXPONENT, m_spotExponent);    
}

为什么我的整个环境都会被统一点亮? 如何在原点0,0,0周围获得一个浓度的光,在1或2个单位距离后逐渐消失?我的起源是网格中的中间立方体。enter image description here

1 个答案:

答案 0 :(得分:1)

警告:当我过去常常摸索OpenGL时,这是“从头到尾”。

我认为“定向光”的OpenGL概念有点像无穷远处的点光源,这意味着光矢量在整个场景中都是不变的。

为了做聚光效果,你需要形成光方向和光矢量(从顶点到光的矢量)的点积,并随着角度的增加以指数方式衰减光。

我记得曾经读过一篇关于这个的教程,会搜索......

是的,它描述了here 向下滚动到“聚光灯”的描述。

在您列出的代码中,我认为您需要确保m_spotExponent大于零才能获得“锥形”效果。较高的值会产生从锥形的“亮”到“暗”部分的“更尖锐”过渡(我认为)。

希望有所帮助