I am trying to draw a rotating cubic and add a spot light in a fixed position in front of this cubic. But because i set the wrong value in z-axis, the light don't show up. After i tried different position of light, the cubic finally displays as i wished. But i still don't know why this value works.
Here is the wrong code. But i think the value is reasonable.
Matrix.setIdentityM(mLightModelMatrix, 0);
Matrix.translateM(mLightModelMatrix, 0, 0.0f, 0.0f, 0.5f);
Matrix.multiplyMV(mLightPosInWorldSpace, 0, mLightModelMatrix, 0, mLightPosInModelSpace, 0);
Matrix.multiplyMV(mLightPosInEyeSpace, 0, mViewMatrix, 0, mLightPosInWorldSpace, 0);
GLES20.glUniform3f(muLightPosHandler,
mLightPosInEyeSpace[0],
mLightPosInEyeSpace[1],
mLightPosInEyeSpace[2]);
Here is the right code. But i don't know why it works.
Matrix.setIdentityM(mLightModelMatrix, 0);
Matrix.translateM(mLightModelMatrix, 0, 0.0f, 0.0f, 2.8f);
Matrix.multiplyMV(mLightPosInWorldSpace, 0, mLightModelMatrix, 0, mLightPosInModelSpace, 0);
Matrix.multiplyMV(mLightPosInEyeSpace, 0, mViewMatrix, 0, mLightPosInWorldSpace, 0);
GLES20.glUniform3f(muLightPosHandler,
mLightPosInEyeSpace[0],
mLightPosInEyeSpace[1],
mLightPosInEyeSpace[2]);
The difference between these two snippets is only the z-axis of light position. You can get all source code from here.
The reason i think 0.0f, 0.0f, 0.5f
is a reasonable position is that the center point of the cubic front face is 0.0f, 0,0f, 0.5f
before transformation. So it will give the cubic strongest light.
It's because you have a spot light which is defined by a light cone. At any distance before 2.8 the cone isn't wide enough to light the entire cube, as demonstrated by this picture:
To get the whole face of the cube to be lit you either need to move the light further away (as you have found) or widen the light cone.
With only two triangles per face you won't get much lighting in the first case as none of the vertices are lit. It's the light on the vertices that determine the light on the face. If you break the model down into more faces you'll see the effect.