1 前言
????????Blinn改进的冯氏光照模型?中只展示了光照效果,本文将进一步展示阴影效果。
? ? ? ? 绘制阴影,需要用到深度纹理,即从光源角度看模型并绘制一张纹理图,纹理图的颜色代表了模型上的点离光源的深度,只有离光源较近的点才会绘制到深度纹理图中,被遮挡的点不会被绘制到深度纹理图中。判断地平面中的点是否处于阴影中,需要将此点变换到光源坐标系中,然后计算变换后的点离光源的深度,判断此深度是否大于纹理图中相应位置的深度,如果大于说明此点在阴影中。
????????读者如果对 OpenGL??ES 不太熟悉,请回顾以下内容:
????????本文完整代码资源见→光影(光照与阴影)效果。?
????????项目目录如下:?
2 案例
????????MainActivity.java
package com.zhyan8.shadowMapping.activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.zhyan8.shadowMapping.opengl.MyGLSurfaceView;
import com.zhyan8.shadowMapping.opengl.MyRender;
public class MainActivity extends AppCompatActivity {
private MyGLSurfaceView mGLSurfaceView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new MyGLSurfaceView(this);
MyRender renderer = new MyRender(getResources());
mGLSurfaceView.setRenderer(renderer);
setContentView(mGLSurfaceView);
}
}
????????MyGLSurfaceView.java
package com.zhyan8.shadowMapping.opengl;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
public class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context) {
super(context);
setEGLContextClientVersion(3);
}
public MyGLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
setEGLContextClientVersion(3);
}
}
????????MyRender.java
package com.zhyan8.shadowMapping.opengl;
import android.content.res.Resources;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import com.zhyan8.shadowMapping.scene.Scene;
import com.zhyan8.shadowMapping.scene.ShadowMap;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MyRender implements GLSurfaceView.Renderer {
private ShadowMap mShadowMap; // 阴影场景
private Scene mScene; // 模型场景
public MyRender(Resources resources) {
mShadowMap = new ShadowMap(resources);
mScene = new Scene(resources);
mShadowMap.addModels(mScene.getModels());
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES30.glClearColor(0.30f, 0.65f, 0.86f, 1.0f);
GLES30.glEnable(GLES30.GL_DEPTH_TEST);
mShadowMap.onSceneCreate();
mScene.onSceneCreate();
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES30.glViewport(0, 0, width, height);
mShadowMap.onSceneChange(width, height);
mScene.onSceneChange(width, height);
mScene.setTextureId(mShadowMap.getTextureId());
}
@Override
public void onDrawFrame(GL10 gl) {
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT);
mShadowMap.onSceneDraw();
mScene.onSceneDraw();
}
}
? ? ? ??AbsScene.java
package com.zhyan8.shadowMapping.scene;
import android.content.res.Resources;
import com.zhyan8.shadowMapping.model.AbsModel;
import java.util.ArrayList;
public abstract class AbsScene {
protected Resources mResources;
protected ArrayList<AbsModel> mModels; // 场景中的模型
protected int mProgramId; // 程序id
protected int mEyePosHandle;
protected int mModelMatrixHandle;
protected int mMvpMatrixHandle;
protected float[] mEyePos; // 眼睛位置
protected float[] mLightPos; // 光源位置
protected float[] mModelMatrix; // 当前正在绘制的模型的模型变换
protected float[] mMvpMatrix; // 当前正在绘制的模型的mvp矩阵变换
public AbsScene(Resources resources) {
mResources = resources;
mModels = new ArrayList<>();
}
// 场景创建
public abstract void onSceneCreate();
// 场景参数改变
public abstract void onSceneChange(int width, int height);
// 绘制场景
public abstract void onSceneDraw();
// 给场景添加模型
public void addModels(ArrayList<AbsModel> models) {
mModels.addAll(models);
}
// 获取场景中的模型
public ArrayList<AbsModel> getModels() {
return mModels;
}
}
? ? ? ??Scene.java
package com.zhyan8.shadowMapping.scene;
import android.content.res.Resources;
import android.opengl.GLES30;
import com.zhyan8.shadowMapping.R;
import com.zhyan8.shadowMapping.model.AbsModel;
import com.zhyan8.shadowMapping.model.Ball;
import com.zhyan8.shadowMapping.model.Cube;
import com.zhyan8.shadowMapping.model.MyTransform;
import com.zhyan8.shadowMapping.model.Plane;
import com.zhyan8.shadowMapping.utils.ShaderUtils;
public class Scene extends AbsScene {
private Light mLight; // 光源对象,管理光的相关属性
private int mModelColorHandle;
private int mMaterialHandle;;
private int mCanObscuredHandle;
private int mShadowMvpMatrixHandle;
private float[] mModelColor; // 当前正在绘制的模型的颜色
private float[] mModelMaterial; // 当前正在绘制的模型的材质,对环境光、漫反射光、镜面光的反射系数
private int mCanObscured; // 当前正在绘制的模型是否能被其他模型遮挡
private float[] mShadowMvpMatrix; // 当前正在绘制的模型的阴影的mvp矩阵
private int mTextureId; // 阴影深度纹理id
public Scene(Resources resources) {
super(resources);
mModels.add(new Plane(resources));
mModels.add(new Cube(resources));
mModels.add(new Ball(resources));
mLight = new Light();
mEyePos = new float[] {0.0f, 6.0f, 9.0f};
mLightPos = mLight.getLightPos();
mModels.forEach(model -> {
model.setEyePos(mEyePos);
model.setLightPos(mLightPos);
model.setCallback(1, mCallback);
});
}
@Override
public void onSceneCreate() {
mProgramId = ShaderUtils.createProgram(mResources, R.raw.scene_vertex_shader, R.raw.scene_fragment_shader);
getHandle();
mLight.initLight(mProgramId);
mModels.forEach(model -> model.onModelCreate());
}
@Override
public void onSceneChange(int width, int height) {
mModels.forEach(model -> model.onModelChange(width, height));
}
@Override
public void onSceneDraw() {
GLES30.glUseProgram(mProgramId);
mLight.openLight();
GLES30.glActiveTexture(GLES30.GL_TEXTURE);
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mTextureId);
mModels.forEach(model -> {
model.setDrawingShadow(false);
model.onModelDraw();
});
}
public void setTextureId(int textureId) {
mTextureId = textureId;
}
private void getHandle() {
mModelColorHandle = GLES30.glGetUniformLocation(mProgramId, "uModelColor");
mMaterialHandle = GLES30.glGetUniformLocation(mProgramId, "uMaterial");
mCanObscuredHandle = GLES30.glGetUniformLocation(mProgramId, "uCanObscured");
mEyePosHandle = GLES30.glGetUniformLocation(mProgramId, "uEyePos");
mModelMatrixHandle = GLES30.glGetUniformLocation(mProgramId, "uModelMatrix");
mMvpMatrixHandle = GLES30.glGetUniformLocation(mProgramId, "uMvpMatrix");
mShadowMvpMatrixHandle = GLES30.glGetUniformLocation(mProgramId, "uShadowMvpMatrix");
}
private void loadValue(AbsModel model) {
mModelColor = model.getColor();
mModelMaterial = model.getMaterial();
mCanObscured = model.canObscured() ? GLES30.GL_TRUE : GLES30.GL_FALSE;
mModelMatrix = model.getModelMatrix();
mMvpMatrix = model.getMvpMatrix();
mShadowMvpMatrix = model.getShadowMvpMatrix();
}
private void injectValue() {
GLES30.glUniform4f(mModelColorHandle, mModelColor[0], mModelColor[1], mModelColor[2], mModelColor[3]);
GLES30.glUniform3f(mMaterialHandle, mModelMaterial[0], mModelMaterial[1], mModelMaterial[2]);
GLES30.glUniform1ui(mCanObscuredHandle, mCanObscured);
GLES30.glUniform3f(mEyePosHandle, mEyePos[0], mEyePos[1], mEyePos[2]);
GLES30.glUniformMatrix4fv(mModelMatrixHandle, 1, false, mModelMatrix, 0);
GLES30.glUniformMatrix4fv(mMvpMatrixHandle, 1, false, mMvpMatrix, 0);
GLES30.glUniformMatrix4fv(mShadowMvpMatrixHandle, 1, false, mShadowMvpMatrix, 0);
}
MyTransform.Callback mCallback = (model) -> {
loadValue(model);
injectValue();
};
}
? ? ? ??ShadowMap.java
package com.zhyan8.shadowMapping.scene;
import android.content.res.Resources;
import android.graphics.Point;
import android.opengl.GLES30;
import com.zhyan8.shadowMapping.R;
import com.zhyan8.shadowMapping.model.MyTransform;
import com.zhyan8.shadowMapping.utils.ShaderUtils;
import com.zhyan8.shadowMapping.utils.TextureUtils;
// ShadowMap用于绘制一个深度纹理, 保存了空间中离光源较近点的深度, 最终返回一个纹理id, 用于判断模型中的点是否被遮挡
public class ShadowMap extends AbsScene {
private int[] mFboId = new int[1];
private int[] mTextureId = new int[1];
public ShadowMap(Resources resources) {
super(resources);
}
@Override
public void onSceneCreate() {
mProgramId = ShaderUtils.createProgram(mResources, R.raw.depth_vertex_shader, R.raw.depth_fragment_shader);
getHandle();
mModels.forEach(model -> model.setCallback(0, mCallback));
}
@Override
public void onSceneChange(int width, int height) {
Point viewportSize = new Point(width, height);
TextureUtils.loadTexture(mFboId, mTextureId, viewportSize);
}
@Override
public void onSceneDraw() {
GLES30.glUseProgram(mProgramId);
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFboId[0]);
mModels.forEach(model -> {
model.setDrawingShadow(true);
model.onModelDraw();
});
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, GLES30.GL_NONE);
}
public int getTextureId() {
return mTextureId[0];
}
private void getHandle() {
mMvpMatrixHandle = GLES30.glGetUniformLocation(mProgramId, "uMvpMatrix");
}
MyTransform.Callback mCallback = (model) -> {
mMvpMatrix = model.getMvpMatrix();
GLES30.glUniformMatrix4fv(mMvpMatrixHandle, 1, false, mMvpMatrix, 0);
};
}
? ? ? ??Light.java?
package com.zhyan8.shadowMapping.scene;
import android.opengl.GLES30;
public class Light {
private int mProgramId;
private int mLightPosHandle;
private int mAmbientLightColorHandle;
private int mLightColorHandle;
private float[] mLightPos = new float[] {0.0f, 10.0f, 0.0f};
private float[] mAmbientLightColor = new float[] {0.5f, 0.5f, 0.5f}; // 环境光颜色
private float[] mLightColor = new float[] {1.0f, 1.0f, 1.0f, 1.0f}; // 光源颜色
public void initLight(int programId) {
mProgramId = programId;
mLightPosHandle = GLES30.glGetUniformLocation(mProgramId, "uLightPos");
mAmbientLightColorHandle = GLES30.glGetUniformLocation(mProgramId, "uAmbientLightColor");
mLightColorHandle = GLES30.glGetUniformLocation(mProgramId, "uLightColor");
}
public void openLight() {
// 光源位置
GLES30.glUniform3f(mLightPosHandle, mLightPos[0], mLightPos[1], mLightPos[2]);
// 环境光颜色
GLES30.glUniform3f(mAmbientLightColorHandle, mAmbientLightColor[0], mAmbientLightColor[1], mAmbientLightColor[2]);
// 光源颜色
GLES30.glUniform3f(mLightColorHandle, mLightColor[0], mLightColor[1], mLightColor[2]);
}
public float[] getLightPos() {
return mLightPos;
}
}
? ? ? ??AbsModel.java
package com.zhyan8.shadowMapping.model;
import android.content.res.Resources;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public abstract class AbsModel {
protected static final int VERTEX_DIMENSION = 3;
protected Resources mResources;
protected MyTransform mTransform;
protected float[][] mVertex; // 顶点坐标
protected float[][] mNorm; // 法线向量
protected float[] mColor; // 模型颜色
protected float[] mMaterial; // 模型材质对环境光、漫反射光、镜面光的反射系数
protected FloatBuffer[] mVertexBuffer;
protected FloatBuffer[] mNormBuffer;
protected int mDrawNum; // 绘制次数
protected int mVertexNumPerDrawUnit; // 每次绘制顶点数
protected boolean mIsDrawingShadow; // 是否正在绘制阴影
protected boolean mCanObscured; // 当前模型是否能被其他模型遮挡
public AbsModel(Resources resources) {
mResources = resources;
mTransform = new MyTransform(this);
}
// 模型创建
public abstract void onModelCreate();
// 模型参数变化
public abstract void onModelChange(int width, int height);
// 模型绘制
public abstract void onModelDraw();
public float[] getColor() {
return mColor;
}
public float[] getMaterial() {
return mMaterial;
}
public boolean canObscured() {
return mCanObscured;
}
public void setEyePos(float[] eyePos) {
mTransform.compEyeViewMatrix(eyePos);
}
public void setLightPos(float[] lightPos) {
mTransform.compLightViewMatrix(lightPos);
}
public void setDrawingShadow(boolean isDrawing) {
mIsDrawingShadow = isDrawing;
mTransform.setDrawingShadow(isDrawing);
}
public float[] getModelMatrix() {
return mTransform.getModelMatrix();
}
public float[] getMvpMatrix() {
return mTransform.getMvpMatrix();
}
public float[] getShadowMvpMatrix() {
return mTransform.getShadowMvpMatrix();
}
public void setCallback(int index, MyTransform.Callback callback) {
mTransform.setCallback(index, callback);
}
public static FloatBuffer getFloatBuffer(float[] floatArr) {
FloatBuffer fb = ByteBuffer.allocateDirect(floatArr.length * Float.BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
fb.put(floatArr);
fb.position(0);
return fb;
}
}
? ? ? ??Plane.java
package com.zhyan8.shadowMapping.model;
import android.content.res.Resources;
import android.opengl.GLES30;
import java.nio.FloatBuffer;
public class Plane extends AbsModel {
public Plane(Resources resources) {
super(resources);
mDrawNum = 1;
mVertexNumPerDrawUnit = 4;
mVertexBuffer = new FloatBuffer[mDrawNum];
mNormBuffer = new FloatBuffer[mDrawNum];
mColor = new float[] {0.9f, 0.9f, 0.9f, 1.0f};
mMaterial = new float[] {0.1f, 0.7f, 0.2f};
mCanObscured = true;
}
@Override
public void onModelCreate() {
mTransform.onTransformCreate();
getVertexAndNorm();
}
@Override
public void onModelChange(int width, int height) {
mTransform.onTransformChange(width, height);
}
@Override
public void onModelDraw() {
mTransform.onTransformExecute();
GLES30.glEnableVertexAttribArray(0);
GLES30.glVertexAttribPointer(0, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mVertexBuffer[0]);
if (!mIsDrawingShadow) {
GLES30.glEnableVertexAttribArray(1);
GLES30.glVertexAttribPointer(1, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mNormBuffer[0]);
}
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_FAN, 0, mVertexNumPerDrawUnit);
GLES30.glDisableVertexAttribArray(0);
if (!mIsDrawingShadow) {
GLES30.glDisableVertexAttribArray(1);
}
}
private void getVertexAndNorm() {
float s = 8f;
float b = -5f;
mVertex = new float[][] {{
-s, b, -s,
-s, b, s,
s, b, s,
s, b, -s}
};
mNorm = new float[][] {{
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f}
};
mVertexBuffer[0] = getFloatBuffer(mVertex[0]);
mNormBuffer[0] = getFloatBuffer(mNorm[0]);
}
}
????????Cube.java
package com.zhyan8.shadowMapping.model;
import android.content.res.Resources;
import android.opengl.GLES30;
import java.nio.FloatBuffer;
public class Cube extends AbsModel {
public Cube(Resources resources) {
super(resources);
mDrawNum = 6;
mVertexNumPerDrawUnit = 4;
mVertexBuffer = new FloatBuffer[mDrawNum];
mNormBuffer = new FloatBuffer[mDrawNum];
mColor = new float[] {0.4f, 0.8f, 0.2f, 1.0f};
mMaterial = new float[] {0.3f, 0.8f, 0.2f};
mCanObscured = false;
}
@Override
public void onModelCreate() {
mTransform.onTransformCreate();
getVertexAndNorm();
}
@Override
public void onModelChange(int width, int height) {
mTransform.onTransformChange(width, height);
}
@Override
public void onModelDraw() {
mTransform.updateRotateAngle();
mTransform.onTransformExecute();
draw();
}
private void draw() {
GLES30.glEnableVertexAttribArray(0);
if (!mIsDrawingShadow) {
GLES30.glEnableVertexAttribArray(1);
}
for (int i = 0; i < mDrawNum; i ++) {
GLES30.glVertexAttribPointer(0, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mVertexBuffer[i]);
if (!mIsDrawingShadow) {
GLES30.glVertexAttribPointer(1, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mNormBuffer[i]);
}
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_FAN, 0, mVertexNumPerDrawUnit);
}
GLES30.glDisableVertexAttribArray(0);
if (!mIsDrawingShadow) {
GLES30.glDisableVertexAttribArray(1);
}
}
private void getVertexAndNorm() {
float s = 1f;
mVertex = new float[][] {
// 后面
{-s, -s, -s,
s, -s, -s,
s, s, -s,
-s, s, -s},
// 前面
{-s, -s, s,
s, -s, s,
s, s, s,
-s, s, s},
// 左面
{-s, s, s,
-s, s, -s,
-s, -s, -s,
-s, -s, s},
// 右面
{s, s, s,
s, s, -s,
s, -s, -s,
s, -s, s},
// 下面
{-s, -s, -s,
s, -s, -s,
s, -s, s,
-s, -s, s},
// 上面
{-s, s, -s,
s, s, -s,
s, s, s,
-s, s, s}
};
mNorm = new float[][] {
// 后面
{0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f},
// 前面
{0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f},
// 左面
{-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f},
// 右面
{1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f},
// 下面
{0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f},
// 上面
{0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f}
};
for (int i = 0; i < mDrawNum; i++) {
mVertexBuffer[i] = getFloatBuffer(mVertex[i]);
mNormBuffer[i] = getFloatBuffer(mNorm[i]);
}
}
}
????????Ball.java
package com.zhyan8.shadowMapping.model;
import android.content.res.Resources;
import android.opengl.GLES30;
import java.nio.FloatBuffer;
public class Ball extends AbsModel {
private static final float BALL_RADIUS = 1.5f; // 球半径
private static final int RING_NUM = 100; // 环数(纬度)
private static final int RAW_NUM = 100; // 射线数(经度)
private static final float RING_WIDTH = (float) (Math.PI / RING_NUM); // 环宽度(维度刻度)
private static final float RAW_GAP_ANGLE = (float) (2 * Math.PI / RAW_NUM); // 两条射线间最小夹角(经度刻度)
public Ball(Resources resources) {
super(resources);
mVertexNumPerDrawUnit = (RAW_NUM + 1) * 2;
mVertex = new float[RING_NUM][mVertexNumPerDrawUnit * VERTEX_DIMENSION];
mVertexBuffer = new FloatBuffer[RING_NUM];
mNormBuffer = new FloatBuffer[RING_NUM];
mColor = new float[] {0.8f, 0.3f, 0.2f, 1.0f};
mMaterial = new float[] {0.6f, 0.8f, 0.5f};
mCanObscured = false;
}
@Override
public void onModelCreate() {
computeVertexAndNorm();
mTransform.onTransformCreate();
}
@Override
public void onModelChange(int width, int height) {
mTransform.onTransformChange(width, height);
}
@Override
public void onModelDraw() {
mTransform.updateTranslate();
mTransform.onTransformExecute();
draw();
}
private void draw() {
GLES30.glEnableVertexAttribArray(0);
if (!mIsDrawingShadow) {
GLES30.glEnableVertexAttribArray(1);
}
for (int i = 0; i < RING_NUM; i++) { // 一环一环绘制模型
GLES30.glVertexAttribPointer(0, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mVertexBuffer[i]);
if (!mIsDrawingShadow) {
GLES30.glVertexAttribPointer(1, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mNormBuffer[i]);
}
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mVertexNumPerDrawUnit);
}
GLES30.glDisableVertexAttribArray(0);
if (!mIsDrawingShadow) {
GLES30.glDisableVertexAttribArray(1);
}
}
// 计算顶点坐标与法线
private void computeVertexAndNorm() {
for (int i = 0; i < RING_NUM; i++) {
getRingVertex(i);
mVertexBuffer[i] = getFloatBuffer(mVertex[i]);
mNormBuffer[i] = getFloatBuffer(mVertex[i]);
}
}
// 计算每环顶点坐标
private void getRingVertex(int ring) {
float phi1 = ring * RING_WIDTH;
float phi2 = phi1 + RING_WIDTH;
float theta = 0f;
int index = 0;
for (int i = 0; i <= RAW_NUM; i++) {
mVertex[ring][index++] = (float) (BALL_RADIUS * Math.sin(phi1) * Math.cos(theta));
mVertex[ring][index++] = (float) (BALL_RADIUS * Math.sin(phi1) * Math.sin(theta));
mVertex[ring][index++] = (float) (BALL_RADIUS * Math.cos(phi1));
mVertex[ring][index++] = (float) (BALL_RADIUS * Math.sin(phi2) * Math.cos(theta));
mVertex[ring][index++] = (float) (BALL_RADIUS * Math.sin(phi2) * Math.sin(theta));
mVertex[ring][index++] = (float) (BALL_RADIUS * Math.cos(phi2));
theta += RAW_GAP_ANGLE;
}
}
}
? ? ? ??MyTransform.java
package com.zhyan8.shadowMapping.model;
import android.opengl.Matrix;
public class MyTransform {
private static final int SCENE_NUM = 2;
private static final int INDEX_SHADOW = 0;
private static final int INDEX_SCENE = 1;
private AbsModel mModel;
private Callback mCallback;
private Callback[] mTempCallback;
private float[] mModelMatrix;
private float[] mViewMatrix;
private float[] mProjectionMatrix;
private float[] mMvpMatrix;
private int mSceneIndex = 0;
private float[][] mTempViewMatrix;
private float[][] mTempProjectionMatrix;
private float[][] mTempMvpMatrix;
private float mViewportRatio;
private float mTheta = 0;
private float mThetaGap = 0.03f;
private float mTranslateRadius = 3.2f;
private float[] mTranslate = new float[] {0f, 0f, 0f};
private int mRotateAngle = 0;
protected boolean mIsDrawingShadow;
public MyTransform(AbsModel model) {
mModel = model;
mTempCallback = new Callback[SCENE_NUM];
mTempViewMatrix = new float[SCENE_NUM][];
mTempProjectionMatrix = new float[SCENE_NUM][];
mTempMvpMatrix = new float[SCENE_NUM][];
}
// 变换创建
public void onTransformCreate() {
mModelMatrix = getIdentityMatrix(16, 0);
mTempMvpMatrix[INDEX_SHADOW] = getIdentityMatrix(16, 0);
mTempMvpMatrix[INDEX_SCENE] = getIdentityMatrix(16, 0);
mTempProjectionMatrix[INDEX_SHADOW] = getIdentityMatrix(16, 0);
mTempProjectionMatrix[INDEX_SCENE] = getIdentityMatrix(16, 0);
}
// 变换参数改变
public void onTransformChange(int width, int height) {
mViewportRatio = 1.0f * width / height;
Matrix.frustumM(mTempProjectionMatrix[INDEX_SHADOW], 0, -mViewportRatio, mViewportRatio, -1f, 1f, 1f, 20.0f);
Matrix.frustumM(mTempProjectionMatrix[INDEX_SCENE], 0, -mViewportRatio, mViewportRatio, -1f, 1f, 1f, 100f);
}
// 变换执行
public void onTransformExecute() {
mModelMatrix = getIdentityMatrix(16, 0);
Matrix.rotateM(mModelMatrix, 0, mRotateAngle, 1, 1, 1);
Matrix.translateM(mModelMatrix, 0, mTranslate[0], mTranslate[1], mTranslate[2]);
// 计算MVP变换矩阵: mvpMatrix = projectionMatrix * viewMatrix * modelMatrix
float[] tempMatrix = new float[16];
Matrix.multiplyMM(tempMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
Matrix.multiplyMM(mMvpMatrix, 0, mProjectionMatrix, 0, tempMatrix, 0);
mCallback.onCall(mModel);
}
// 计算眼睛视觉下的观察矩阵
public void compEyeViewMatrix(float[] eyePos) {
float[] eye = eyePos;
float[] center = new float[] {0, 0, 0};
float[] up = new float[] {0, 1, 0};
mTempViewMatrix[INDEX_SCENE] = getIdentityMatrix(16, 0);
Matrix.setLookAtM(mTempViewMatrix[INDEX_SCENE], 0, eye[0], eye[1], eye[2], center[0], center[1], center[2], up[0], up[1], up[2]);
}
// 计算光源视觉下的观察矩阵
public void compLightViewMatrix(float[] lightPos) {
float[] eye = lightPos;
float[] center = new float[] {0, 0, 0};
float[] up = new float[] {0, 0, 1};
mTempViewMatrix[INDEX_SHADOW] = getIdentityMatrix(16, 0);
Matrix.setLookAtM(mTempViewMatrix[INDEX_SHADOW], 0, eye[0], eye[1], eye[2], center[0], center[1], center[2], up[0], up[1], up[2]);
}
// 设置回调,变换执行完后调用
public void setCallback(int index, Callback callback) {
mTempCallback[index] = callback;
}
// 设置是否处于绘制阴影状态
public void setDrawingShadow(boolean isDrawing) {
mIsDrawingShadow = isDrawing;
if (isDrawing) {
mSceneIndex = INDEX_SHADOW;
} else {
mSceneIndex = INDEX_SCENE;
}
mViewMatrix = mTempViewMatrix[mSceneIndex];
mProjectionMatrix = mTempProjectionMatrix[mSceneIndex];
mMvpMatrix = mTempMvpMatrix[mSceneIndex];
mCallback = mTempCallback[mSceneIndex];
}
// 获取模型矩阵
public float[] getModelMatrix() {
return mModelMatrix;
}
// 获取mvp矩阵
public float[] getMvpMatrix() {
return mMvpMatrix;
}
// 获取阴影的mvp矩阵
public float[] getShadowMvpMatrix() {
return mTempMvpMatrix[INDEX_SHADOW];
}
// 更行旋转角度
public void updateRotateAngle() {
if (!mIsDrawingShadow) {
return;
}
mRotateAngle = (mRotateAngle + 1) % 360;
}
// 更新平移
public void updateTranslate() {
if (!mIsDrawingShadow) {
return;
}
mTheta = mTheta > 360 ? mTheta - 360 + mThetaGap : mTheta + mThetaGap;
mTranslate[0] = (float) (mTranslateRadius * Math.cos(mTheta));
mTranslate[1] = (float) (0.8f * Math.cos(mTheta * 4));
mTranslate[2] = (float) (mTranslateRadius * Math.sin(mTheta));
}
private float[] getIdentityMatrix(int size, int offset) {
float[] matrix = new float[size];
Matrix.setIdentityM(matrix, offset);
return matrix;
}
// 回调,变换执行完后,将计算的相关矩阵注入到着色器程序中
public interface Callback {
void onCall(AbsModel model);
}
}
?? ? ? ?ShaderUtils.java
package com.zhyan8.shadowMapping.utils;
import android.content.res.Resources;
import android.opengl.GLES30;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShaderUtils {
//创建程序id
public static int createProgram(Resources resources, int vertexShaderResId, int fragmentShaderResId) {
final int vertexShaderId = compileShader(resources, GLES30.GL_VERTEX_SHADER, vertexShaderResId);
final int fragmentShaderId = compileShader(resources, GLES30.GL_FRAGMENT_SHADER, fragmentShaderResId);
return linkProgram(vertexShaderId, fragmentShaderId);
}
//通过外部资源编译着色器
private static int compileShader(Resources resources, int type, int shaderId){
String shaderCode = readShaderFromResource(resources, shaderId);
return compileShader(type, shaderCode);
}
//通过代码片段编译着色器
private static int compileShader(int type, String shaderCode){
int shader = GLES30.glCreateShader(type);
GLES30.glShaderSource(shader, shaderCode);
GLES30.glCompileShader(shader);
return shader;
}
//链接到着色器
private static int linkProgram(int vertexShaderId, int fragmentShaderId) {
final int programId = GLES30.glCreateProgram();
//将顶点着色器加入到程序
GLES30.glAttachShader(programId, vertexShaderId);
//将片元着色器加入到程序
GLES30.glAttachShader(programId, fragmentShaderId);
//链接着色器程序
GLES30.glLinkProgram(programId);
return programId;
}
//从shader文件读出字符串
private static String readShaderFromResource(Resources resources, int shaderId) {
InputStream is = resources.openRawResource(shaderId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
}
????????TextureUtils.java
package com.zhyan8.shadowMapping.utils;
import android.graphics.Point;
import android.opengl.GLES30;
public class TextureUtils {
public static void loadTexture(int[] fboId, int[] textureId, Point viewportSize) {
// 生成纹理id
GLES30.glGenTextures(1, textureId, 0);
// 绑定纹理到OpenGL
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId[0]);
// 设置纹理参数
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST);
GLES30.glTexParameteri( GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE );
GLES30.glTexParameteri( GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE );
// 生成FBO
GLES30.glGenFramebuffers(1, fboId, 0);
// 绑定FBO
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fboId[0]);
GLES30.glTexImage2D( GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, viewportSize.x, viewportSize.y, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null);
// 将纹理附着在颜色附着点上
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, textureId[0], 0);
// 取消绑定纹理和FBO
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, GLES30.GL_NONE);
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, GLES30.GL_NONE);
}
}
? ? ? ? depth_vertex_shader.glsl
attribute vec4 aPosition;
uniform mat4 uMvpMatrix;
varying vec4 vPosition;
void main() {
vPosition = uMvpMatrix * aPosition;
gl_Position = vPosition;
}
? ? ? ? depth_fragment_shader.glsl
precision highp float;
varying vec4 vPosition;
void main() {
// 经透视分割后,取值范围:-1~1
float depth = vPosition.z / vPosition.w;
// 归一化到0~1之间
float normDepth = (depth + 1.0) / 2.0;
// 用灰度表示深度
gl_FragColor = vec4(normDepth, normDepth, normDepth, 1.0);
}
? ? ? ? scene_vertex_shader.glsl
attribute vec4 aPosition; // 顶点坐标
attribute vec3 aNormal; // 法线向量
uniform mat4 uMvpMatrix; // mvp矩阵变换
uniform mat4 uShadowMvpMatrix; // 阴影mvp矩阵变换
varying vec4 vPosition; // 顶点坐标
varying vec3 vNormal; // 法线向量
varying mat4 vShadowMvpMatrix; // 阴影mvp变换矩阵
void main() {
gl_Position = uMvpMatrix * aPosition; // 相机视觉看模型
// gl_Position = uShadowMvpMatrix * aPosition; // 灯光视觉看模型
vPosition = aPosition;
vNormal = aNormal;
vShadowMvpMatrix = uShadowMvpMatrix;
}
? ? ? ? scene_fragment_shader.glsl
precision highp float;
uniform vec3 uEyePos; // 观察位置
uniform vec3 uLightPos; // 光源坐标
uniform vec4 uModelColor; // 模型颜色
uniform vec3 uAmbientLightColor; // 环境光颜色
uniform vec3 uLightColor; // 光源颜色(漫反射、镜面反射)
uniform vec3 uMaterial; // 材质对环境光、漫反射光、镜面光的反射系数
uniform mat4 uModelMatrix; // 模型变换
uniform sampler2D uShadowTexture;
uniform bool uCanObscured; // 模型是否能被其他模型遮挡
varying vec4 vPosition; // 顶点坐标
varying vec3 vNormal; // 法线向量
varying mat4 vShadowMvpMatrix; // 阴影mvp矩阵
// 环境光的计算
vec4 ambientColor() {
vec3 ambient = uMaterial.x * uAmbientLightColor;
return vec4(ambient, 1.0);
}
// 漫反射的计算
vec4 diffuseColor() {
// 模型变换后的位置
vec3 fragPos = (uModelMatrix * vPosition).xyz;
// 光照方向
vec3 lightDirection = normalize(uLightPos - fragPos);
// 模型变换后的法线向量
vec3 normal = normalize(mat3(uModelMatrix) * vNormal);
// max(cos(入射角),0)
float diff = max(dot(normal, lightDirection), 0.0);
// 材质的漫反射系数*max(cos(入射角),0)*光照颜色
vec3 diffuse = uMaterial.y * diff * uLightColor;
return vec4(diffuse, 1.0);
}
// 镜面光计算,镜面光计算有两种方式,一种是冯氏模型,一种是Blinn改进的冯氏模型
// 冯氏模型: 材质的镜面反射系数*max(0,cos(反射向量与观察向量夹角)^粗糙度*光照颜色
// Blinn改进的冯氏模型: 材质的镜面反射系数*max(0,cos(半向量与法向量的夹角)^粗糙度*光照颜色
// 这里使用的是改进的冯氏模型,基于Half-Vector的计算方式
vec4 specularColor() {
// 模型变换后的位置
vec3 fragPos = (uModelMatrix * vPosition).xyz;
// 光照方向
vec3 lightDirection = normalize(uLightPos - fragPos);
// 模型变换后的法线向量
vec3 normal = normalize(mat3(uModelMatrix) * vNormal);
// 观察方向
vec3 viewDirection = normalize(uEyePos - fragPos);
// 半向量(观察向量与光照向量的半向量)
vec3 hafVector = normalize(lightDirection + viewDirection);
// max(0,cos(半向量与法向量的夹角)^粗糙度
float diff = pow(max(dot(normal, hafVector), 0.0), 4.0);
vec3 specular = uMaterial.z * diff * uLightColor;
return vec4(specular, 1.0);
}
// 是否处于阴影中
bool isInShadow() {
if (!uCanObscured) {
return false;
}
// 经透视分割后,取值范围:-1~1
vec4 shadowCoord = vShadowMvpMatrix * vPosition;
vec3 shadowMapPos = shadowCoord.xyz / shadowCoord.w;
// 归一化到0~1之间
vec3 normPos = (shadowMapPos + 1.0) / 2.0;
// 在shadow map中查找normPos.xy处离光源最近的点的深度
vec4 color = texture2D(uShadowTexture, normPos.xy);
// gl_FragColor = color; // 显示深度纹理
float depth = color.x;
if (normPos.z > depth + 0.00001) {
return true;
}
return false;
}
void main() {
float shadow = isInShadow() ? 0.4 : 1.0;
vec4 color = (ambientColor() + diffuseColor() + specularColor()) * uModelColor * shadow;
gl_FragColor = color;
}
3 运行效果
? ? ? ? 1)深度纹理图
? ? ? ? 2)光影图
|