初次提交

This commit is contained in:
2022-09-19 18:05:01 +08:00
commit 57051fc44b
5401 changed files with 325410 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample13_3</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Wed Aug 24 20:01:34 CST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto" package="com.bn.Sample13_3">
<uses-sdk android:minSdkVersion="8"></uses-sdk>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Sample13_3_Activity"
android:label="@string/app_name"
android:launchMode="singleTask"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,27 @@
precision mediump float;
varying vec2 vTextureCoord; //接收纹理坐标参数
varying float vertexHeight;//接受顶点的高度值
uniform sampler2D sTextureSand;//纹理内容数据 ----沙滩
uniform sampler2D sTextureGrass;//纹理内容数据-----草地
void main()
{
float height1=15.0;
float height2=25.0;
vec4 finalSand=texture2D(sTextureSand, vTextureCoord);//沙滩
vec4 finalGrass=texture2D(sTextureGrass, vTextureCoord); //草地
if(vertexHeight<height1)//绘制沙滩
{
gl_FragColor = finalSand;
}
else if(vertexHeight<height2)//绘制草地和沙滩混合层
{
float ratio=(vertexHeight-height1)/(height2-height1);
finalSand *=(1.0-ratio);
finalGrass *=ratio;
gl_FragColor =finalGrass+ finalSand;
}
else//绘制草地
{
gl_FragColor = finalGrass;
}
}

View File

@@ -0,0 +1,7 @@
precision mediump float;
varying vec2 vTextureCoord; //接收从顶点着色器过来的参数
uniform sampler2D sTexture;//纹理内容数据
void main()
{
gl_FragColor=texture2D(sTexture, vTextureCoord);
}

View File

@@ -0,0 +1,9 @@
precision mediump float;
varying vec2 vTextureCoord; //接收从顶点着色器过来的参数
uniform sampler2D sTexture;//纹理内容数据
varying vec3 vVertexCoord;
void main()
{
//给此片元从纹理中采样出颜色值
gl_FragColor = texture2D(sTexture, vTextureCoord);
}

View File

@@ -0,0 +1,8 @@
precision mediump float;
varying vec2 vTextureCoord; //接收从顶点着色器过来的参数
uniform sampler2D sTexture;//纹理内容数据
void main()
{
//将计算出的颜色给此片元
gl_FragColor=texture2D(sTexture, vTextureCoord);
}

View File

@@ -0,0 +1,8 @@
precision mediump float;
varying vec2 vTextureCoord; //接收从顶点着色器过来的参数
uniform sampler2D sTexture;//纹理内容数据
void main()
{
//给此片元从纹理中采样出颜色值
gl_FragColor = texture2D(sTexture, vTextureCoord);
}

View File

@@ -0,0 +1,12 @@
//山地的顶点着色器
uniform mat4 uMVPMatrix; //总变换矩阵
attribute vec3 aPosition; //顶点位置
attribute vec2 aTexCoor; //顶点纹理坐标
varying vec2 vTextureCoord; //用于传递给片元着色器的变量
varying float vertexHeight;//接受顶点的高度值
void main()
{
gl_Position = uMVPMatrix * vec4(aPosition,1); //根据总变换矩阵计算此次绘制此顶点位置
vTextureCoord = aTexCoor;//将接收的纹理坐标传递给片元着色器
vertexHeight = aPosition.y;//将该顶点的高度传入片元着色器
}

View File

@@ -0,0 +1,10 @@
//叶子的顶点着色器
uniform mat4 uMVPMatrix; //总变换矩阵
attribute vec3 aPosition; //顶点位置
attribute vec2 aTexCoor; //顶点纹理坐标
varying vec2 vTextureCoord; //用于传递给片元着色器的变量
void main()
{
gl_Position = uMVPMatrix * vec4(aPosition,1); //根据总变换矩阵计算此次绘制此顶点位置
vTextureCoord = aTexCoor;//将接收的纹理坐标传递给片元着色器
}

View File

@@ -0,0 +1,12 @@
uniform mat4 uMVPMatrix; //总变换矩阵
attribute vec3 aPosition; //顶点位置
attribute vec2 aTexCoor; //顶点纹理坐标
varying vec2 vTextureCoord; //用于传递给片元着色器的变量
varying vec3 vVertexCoord;
void main()
{
gl_Position = uMVPMatrix * vec4(aPosition,1); //根据总变换矩阵计算此次绘制此顶点位置
vTextureCoord = aTexCoor;//将接收的纹理坐标传递给片元着色器
vVertexCoord = aPosition;
}

View File

@@ -0,0 +1,29 @@
//这里是树干节点的顶点着色器
//这里的所有的偏转角都是相对于Z轴正方向来说的逆时针旋转的
uniform mat4 uMVPMatrix; //总变换矩阵
uniform float bend_R;//这里指的是树的弯曲半径
uniform float direction_degree;//这里指的风向,用角度表示的沿Z轴正方向逆时针旋转
attribute vec3 aPosition; //顶点位置
attribute vec2 aTexCoor; //顶点纹理坐标
varying vec2 vTextureCoord; //用于传递给片元着色器的变量
void main()
{
//计算当前的弧度
float curr_radian=aPosition.y/bend_R;
//计算当前点的结果高度
float result_height=bend_R*sin(curr_radian);
//计算当前点的增加的长度
float increase=bend_R-bend_R*cos(curr_radian);
//计算当前点最后的x坐标
float result_X=aPosition.x+increase*sin(radians(direction_degree));
//计算当前点最后的z坐标
float result_Z=aPosition.z+increase*cos(radians(direction_degree));
//最后结果
vec4 result_point=vec4(result_X,result_height,result_Z,1.0);
gl_Position = uMVPMatrix * result_point; //根据总变换矩阵计算此次绘制此顶点位置
vTextureCoord = aTexCoor;//将接收的纹理坐标传递给片元着色器
}

View File

@@ -0,0 +1,28 @@
uniform mat4 uMVPMatrix; //总变换矩阵
uniform float uStartAngle;//本帧起始角度
uniform float uWidthSpan;//横向长度总跨度
attribute vec3 aPosition; //顶点位置
attribute vec2 aTexCoor; //顶点纹理坐标
varying vec2 vTextureCoord; //用于传递给片元着色器的变量
void main()
{
//计算X向角度
float angleSpanH=30.0*3.14159265;//横向角度总跨度
float startX=0.0;//起始X坐标
//根据横向角度总跨度、横向长度总跨度及当前点X坐标折算出当前点X坐标对应的角度
float currAngleH=uStartAngle+((aPosition.x-startX)/uWidthSpan)*angleSpanH;
//计算出随z向发展起始角度的扰动值
float startZ=0.0;//起始z坐标
//根据纵向角度总跨度、纵向长度总跨度及当前点Y坐标折算出当前点Y坐标对应的角度
float currAngleZ=((aPosition.z-startZ)/uWidthSpan)*angleSpanH;
//计算斜向波浪
float tzH=sin(currAngleH-currAngleZ)*0.8;
//根据总变换矩阵计算此次绘制此顶点位置
gl_Position = uMVPMatrix * vec4(aPosition.x,tzH,aPosition.z,1);
// gl_Position = uMVPMatrix * vec4(aPosition,1);
vTextureCoord = aTexCoor;//将接收的纹理坐标传递给片元着色器
}

View File

@@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8

View File

@@ -0,0 +1,38 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bn.Sample13_3;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int caodi=0x7f020000;
public static final int coconut=0x7f020001;
public static final int icon=0x7f020002;
public static final int land=0x7f020003;
public static final int sand=0x7f020004;
public static final int sky=0x7f020005;
public static final int water=0x7f020006;
}
public static final class id {
public static final int seekbar_sb=0x7f060001;
public static final int seekbar_tv=0x7f060000;
}
public static final class layout {
public static final int seekbar=0x7f030000;
}
public static final class raw {
public static final int gamebg_music=0x7f040000;
public static final int leaves=0x7f040001;
public static final int treetrunk=0x7f040002;
public static final int wind=0x7f040003;
}
public static final class string {
public static final int app_name=0x7f050000;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:id="@+id/seekbar_tv"/>
<SeekBar
android:id="@+id/seekbar_sb"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</SeekBar>
</LinearLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Sample13_3</string>
</resources>

View File

@@ -0,0 +1,229 @@
package com.bn.Sample13_3;
import java.io.IOException;
import java.io.InputStream;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.GLES20;
import android.opengl.GLUtils;
//常量类
public class Constant
{
//系统常量
//屏幕的宽高
public static int SCREEN_WIDTH;
public static int SCREEN_HEIGHT;
//线程标志
public static boolean flag_go=true;
//单位宽度值
public static final float UNIT_SIZE=100;
//太阳光的位置
public static final float[] sunPosition=
{
UNIT_SIZE*31*1.5f, 1000, UNIT_SIZE*31*1.2f
};
//--风吹的属性
public static int wind=5;//当前的风力
public static float wind_force_init=-4.0f;
public static float wind_force=wind_force_init*1.006f;;
public static float wind_speed_init=200;
public static float wind_speed=wind_speed_init;
public static float bend_R_max=5000;
public static float bend_R=bend_R_max;//这里指的是节点圆柱中心到弯曲中心处的长度
public static float wind_direction=0;//这里指的是风向的角度
public static void setWindForce(int windForce)//根据风力级数设置加速度和线程休眠时间
{
wind=windForce;
switch(windForce)
{
case 0:
bend_R=10000;
break;
case 1:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*1.1f;
break;
case 2:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*1.08f;
break;
case 3:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*1.05f;
break;
case 4:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*1.03f;
break;
case 5:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*1.006f;
break;
case 6:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*1.004f;
break;
case 7:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init;
break;
case 8:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*0.999f;
break;
case 9:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*0.998f;
break;
case 10:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*0.997f;
break;
case 11:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*0.996f;
break;
case 12:
bend_R=bend_R_max;
wind_speed=wind_speed_init;
wind_force=wind_force_init*0.9952f;
break;
}
}
//摄像机参数
public static float DISTANCE=3000.0f;//摄像机位置距离观察目标点的距离4700--600
public static final float CAMERA_X=UNIT_SIZE*31*1.5f;//摄像机的观察点
public static final float CAMERA_HEIGHT=80;//摄像机的高度
public static final float CAMERA_Z=UNIT_SIZE*31*1.5f;//摄像机的观察点
public static float camera_direction=225;//摄像机的观察方向//摄像机的方向角初始方向是Z州的负方向,逆时针旋转
public static final float MOVE_SPAN=20f;//摄像机每次移动的位移
//海底的相关参数
public static final float FLOOR_WIDTH=UNIT_SIZE*31;//海底的宽度
public static final float FLOOR_HEIGHT=UNIT_SIZE*31;//海底的高度
public static final float[][] floor_array=//绘制山地的区域0表示海底1表示高山
{
{0,0,0},
{0,1,0},
{0,0,0}
};
//树干的属性
public static float bottom_radius=15f;//树的底端半径
public static float joint_height=15f;//每个节点的高度
public static int joint_num=20;//节点的总共数目
public static int joint_available_num=14;//节点的有效数目
//------------叶子的属性
public static float leaves_width=60f;//叶子的宽度;
public static float leaves_height=60f;//叶子的高度
public static float leaves_offset=-leaves_height/1.4f;//叶子相对于XZ平面的偏移量
public static float leaves_absolute_height=joint_height*joint_available_num;//叶子的绝对高度
public static float tree_YOffset=39.21f;
//表示椰子树位置的矩阵
public static final float[][] MAP_TREE=
{
{FLOOR_WIDTH*1.49f,tree_YOffset,FLOOR_WIDTH*1.54f},
{FLOOR_WIDTH*1.48f,tree_YOffset,FLOOR_WIDTH*1.5f},
{FLOOR_WIDTH*1.47f,tree_YOffset,FLOOR_WIDTH*1.4f},
{FLOOR_WIDTH*1.5f,tree_YOffset,FLOOR_WIDTH*1.49f},
{FLOOR_WIDTH*1.52f,tree_YOffset,FLOOR_WIDTH*1.4f},
{FLOOR_WIDTH*1.48f,tree_YOffset,FLOOR_WIDTH*1.3f},
{FLOOR_WIDTH*1.56f,tree_YOffset,FLOOR_WIDTH*1.35f},
{FLOOR_WIDTH*1.48f,tree_YOffset,FLOOR_WIDTH*1.2f},
};
//----------水面的属性
public static final int ROWS=31*3;//水面的行数
public static final int COLS=31*3;//水面的列数
public static final float WATER_SPAN=UNIT_SIZE;//水面格子的单位间隔
//加载纹理的方法
public static int initTexture(Resources r,int drawableId)//textureId
{
//生成纹理ID
int[] textures = new int[1];
GLES20.glGenTextures
(
1, //产生的纹理id的数量
textures, //纹理id的数组
0 //偏移量
);
int textureId=textures[0];
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_REPEAT);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_REPEAT);
//通过输入流加载图片===============begin===================
InputStream is = r.openRawResource(drawableId);
Bitmap bitmapTmp;
try
{
bitmapTmp = BitmapFactory.decodeStream(is);
}
finally
{
try
{
is.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
//实际加载纹理
GLUtils.texImage2D
(
GLES20.GL_TEXTURE_2D, //纹理类型在OpenGL ES中必须为GL10.GL_TEXTURE_2D
0, //纹理的层次0表示基本图像层可以理解为直接贴图
bitmapTmp, //纹理图像
0 //纹理边框尺寸
);
bitmapTmp.recycle(); //纹理加载成功后释放图片
return textureId;
}
//-----------灰度图相关属性
public static final float LAND_HIGH_ADJUST=0f;//陆地的高度调整值
public static final float LAND_HIGHEST=100f;//陆地最大高差
public static float[][] LAND_ARRAY;//加载的灰度图数据的高度
public static final float LAND_SPAN=UNIT_SIZE ;//陆地的单位宽度
public static void initLand(Resources r,int texId)
{
//从灰度图片中加载陆地上每个顶点的高度
LAND_ARRAY=loadLandforms(r,texId);
}
//从灰度图片中加载陆地上每个顶点的高度
public static float[][] loadLandforms(Resources resources,int texId)
{
Bitmap bt=BitmapFactory.decodeResource(resources, texId);
int colsPlusOne=bt.getWidth();
int rowsPlusOne=bt.getHeight();
float[][] result=new float[rowsPlusOne][colsPlusOne];
for(int i=0;i<rowsPlusOne;i++)
{
for(int j=0;j<colsPlusOne;j++)
{
int color=bt.getPixel(j,i);
int r=Color.red(color);
int g=Color.green(color);
int b=Color.blue(color);
int h=(r+g+b)/3;
result[i][j]=h*LAND_HIGHEST/255-LAND_HIGH_ADJUST;
}
}
return result;
}
//天空球的相关属性
public static final float SKY_BALL_RADIUS=1.49F*FLOOR_WIDTH;//天空球的半径
public static float sky_rotation=0;
}

View File

@@ -0,0 +1,106 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.opengl.GLES20;
/*
* 用于绘制海底
*/
public class FloorRect
{
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maTexCoorHandle; //顶点纹理坐标属性引用
String mVertexShader;//顶点着色器
String mFragmentShader;//片元着色器
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mTexCoorBuffer;//顶点纹理坐标数据缓冲
int vCount=0;
float texSize=5;
public FloorRect(int mProgram,float width,float height)
{
this.mProgram=mProgram;
//初始化顶点坐标与着色数据
initVertexData(width,height);
//初始化shader
initShader();
}
//初始化顶点坐标与着色数据的方法
public void initVertexData(float width,float height)
{
vCount=6;
float vertices[]=new float[]
{
0,0,0,
0,0,height,
width,0,height,
width,0,height,
width,0,0,
0,0,0
};
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为Float型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//顶点纹理坐标数据
float []texCoor=new float[]
{
0,0, 0,texSize, texSize,texSize,
texSize,texSize, texSize,0, 0,0
};
//创建顶点纹理坐标数据缓冲
ByteBuffer cbb = ByteBuffer.allocateDirect(texCoor.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mTexCoorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mTexCoorBuffer.put(texCoor);//向缓冲区中放入顶点着色数据
mTexCoorBuffer.position(0);//设置缓冲区起始位置
}
//初始化shader
public void initShader()
{
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点纹理坐标属性引用
maTexCoorHandle= GLES20.glGetAttribLocation(mProgram, "aTexCoor");
//获取程序中总变换矩阵引用
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
}
public void drawSelf(int texId)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将顶点位置数据传入渲染管线
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//将顶点纹理坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//启用顶点位置、纹理坐标数据数组
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
}

View File

@@ -0,0 +1,261 @@
package com.bn.Sample13_3;
import static com.bn.Sample13_3.Constant.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import com.bn.Sample13_3.R;
import android.content.Context;
import android.content.res.Resources;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
class GameSurfaceView extends GLSurfaceView
{
private SceneRenderer mRenderer;//场景渲染器
static Sample13_3_Activity activty;
float mPreviousY;
float mPreviousX;
//-----纹理
int tex_grassId;//系统分配的草地纹理id
int tex_sandId;
int tex_leavesId;//系统分配的灌木纹理id
int tex_treejointId;//树干的纹理id
int tex_waterId;//水面纹理Id
int tex_skyId;//天空纹理id
//-----物体对象组件
TreesForControl treesForControl;//所有椰子树的控制类
TreeLeaves treeLeaves[];//叶子模型
TreeTrunk treeTrunk;//树干模型
FloorRect floorLand; //草地
SeaWater water;//水面
LandForm landForm;//灰度图山
SkyBall skyBall;//天空球
static float tx=CAMERA_X;//观察目标点x坐标
static float ty=CAMERA_HEIGHT;//观察目标点y坐标
static float tz=CAMERA_Z;//观察目标点z坐标
static float cx=(float) (tx+Math.sin(Math.toRadians(camera_direction))*DISTANCE);//摄像机x坐标
static float cy=CAMERA_HEIGHT;//摄像机y坐标
static float cz=(float) (tz+Math.cos(Math.toRadians(camera_direction))*DISTANCE);//摄像机z坐标
public GameSurfaceView(Context context)
{
super(context);
activty=(Sample13_3_Activity)context;
this.setEGLContextClientVersion(2); //设置使用OPENGL ES2.0
mRenderer = new SceneRenderer(); //创建场景渲染器
setRenderer(mRenderer); //设置渲染器
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);//设置渲染模式为主动渲染
this.setKeepScreenOn(true);
}
//触摸事件回调方法
@Override
public boolean onTouchEvent(MotionEvent e)
{
float y = e.getY();
float x = e.getX();
switch (e.getAction())
{
case MotionEvent.ACTION_DOWN://按下动作
break;
case MotionEvent.ACTION_UP://抬起动作
break;
case MotionEvent.ACTION_MOVE:
float dy = y - mPreviousY;//计算触控笔Y位移
float dx = x - mPreviousX;//计算触控笔X位移
if(dy>5&&DISTANCE>600)//前进
{
DISTANCE-=20;
}
else if(dy<-5&&DISTANCE<4700)//后退
{
DISTANCE+=20;
}
if(dx<-10)//左转弯
{
camera_direction-=dx*0.1f;
}
else if(dx>10)//右转弯
{
camera_direction-=dx*0.1f;
}
break;
}
mPreviousY = y;//记录触控笔位置
mPreviousX = x;//记录触控笔位置
//重新初始化摄像机的位置和方向
cx=(float) (tx+Math.sin(Math.toRadians(camera_direction))*DISTANCE);//摄像机x坐标
cy=CAMERA_HEIGHT;//摄像机y坐标
cz=(float) (tz+Math.cos(Math.toRadians(camera_direction))*DISTANCE);//摄像机z坐标
return true;
}
class SceneRenderer implements GLSurfaceView.Renderer
{
float oldTime=0;
public void onDrawFrame(GL10 gl)
{
float currTime=System.nanoTime();
System.out.println("FPS == "+1000000000.0/(currTime-oldTime));
//清除深度缓冲与颜色缓冲
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
MatrixState.setCamera(cx,cy,cz,tx,ty,tz,0f,1.0f,0.0f);
//天空球旋转
sky_rotation=(sky_rotation+0.03f)%360;
//创建天空
skyBall.drawSelf(tex_skyId,sky_rotation);
//绘制山脉
drawLandForm();
//绘制水面
drawWater();
//绘制正常的椰子树
treesForControl.drawSelf(tex_leavesId,tex_treejointId,bend_R,wind_direction);
oldTime=currTime;
}
public void onSurfaceChanged(GL10 gl, int width, int height)
{
//设置视窗大小及位置
GLES20.glViewport(0, 0, width, height);
//计算GLSurfaceView的宽高比
float ratio = (float) width / height;
//调用此方法计算产生透视投影矩阵
MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 3, 50000);
//调用此方法产生摄像机9参数位置矩阵
MatrixState.setCamera(cx,cy,cz,tx,ty,tz,0f,1.0f,0.0f);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
//设置屏幕背景色RGBA
GLES20.glClearColor(0.0f,0.0f,0.0f,1.0f);
//打开深度检测
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
//打开背面剪裁
GLES20.glEnable(GLES20.GL_CULL_FACE);
//初始化变换矩阵
MatrixState.setInitStack();
//初始化光源位置
MatrixState.setLightLocation(sunPosition[0], sunPosition[1],sunPosition[2]);
//加载shader
ShaderManager.loadCodeFromFile(GameSurfaceView.this.getResources());
//编译shader
ShaderManager.compileShader();
initAllObject();//初始化纹理组件
initAllTexture();//初始化纹理
//创建一个线程,定时摆动树干
new Thread()
{
@Override
public void run()
{
while(flag_go)
{
//椰子树旋转
if(0!=wind)//如果风力为0级以上
{
//设置椰子树的左右摆动
wind_speed+=wind_force;//摆动的速度
bend_R-=wind_speed;//摆动的幅度
if(bend_R>bend_R_max)//智力状态
{
wind_speed=wind_speed_init;
bend_R=bend_R_max;
}
}
try
{
Thread.sleep(50);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}.start();
}
}
//绘制山地的方法
public void drawLandForm()
{
for(int i=0;i<floor_array.length;i++)
{
for(int j=0;j<floor_array[0].length;j++)
{
MatrixState.pushMatrix();
MatrixState.translate(j*FLOOR_WIDTH,0,i*FLOOR_HEIGHT);
if(1==floor_array[i][j])//绘制高山
{
landForm.drawSelf(tex_grassId,tex_sandId);
}
MatrixState.popMatrix();
}
}
}
//绘制水面
public void drawWater()
{
MatrixState.pushMatrix();
MatrixState.translate(0, 3f, 0);
//绘制水面
water.drawSelf(tex_waterId);
MatrixState.popMatrix();
}
//创建所有的物体组件对象
public void initAllObject()
{
//创建树干
treeTrunk=new TreeTrunk
(
ShaderManager.getTreeWaveShaderProgram(),
bottom_radius,
joint_height,
joint_num,
joint_available_num
);
//创建六片树叶
treeLeaves=new TreeLeaves[]
{
new TreeLeaves(ShaderManager.getLeavesShaderProgram(),leaves_width,leaves_height,leaves_offset,0),
new TreeLeaves(ShaderManager.getLeavesShaderProgram(),leaves_width,leaves_height,leaves_offset,1),
new TreeLeaves(ShaderManager.getLeavesShaderProgram(),leaves_width,leaves_height,leaves_offset,2),
new TreeLeaves(ShaderManager.getLeavesShaderProgram(),leaves_width,leaves_height,leaves_offset,3),
new TreeLeaves(ShaderManager.getLeavesShaderProgram(),leaves_width,leaves_height,leaves_offset,4),
new TreeLeaves(ShaderManager.getLeavesShaderProgram(),leaves_width,leaves_height,leaves_offset,5)
};
//创建树的控制类
treesForControl=new TreesForControl(treeTrunk,treeLeaves);
//创建海底
floorLand=new FloorRect
(
ShaderManager.getTextureShaderProgram(),
FLOOR_WIDTH,
FLOOR_HEIGHT
);
//创建水面
water=new SeaWater(ShaderManager.getWaterShaderProgram());
//加载灰度图的山
initLand(getResources(),R.drawable.land);
//创建灰度图山
landForm=new LandForm(LAND_ARRAY,ShaderManager.getLandFormShaderProgram());//灰度图山
//创建天空
skyBall=new SkyBall
(
SKY_BALL_RADIUS,
ShaderManager.getTextureShaderProgram(),
SKY_BALL_RADIUS,
0,
SKY_BALL_RADIUS
);
}
//初始化所有的纹理图形
public void initAllTexture()
{
Resources r=this.getResources();//获取资源
tex_grassId=initTexture(r,R.drawable.caodi);//草地纹理
tex_sandId=initTexture(r,R.drawable.sand);//沙滩纹理
tex_leavesId=initTexture(r,R.drawable.coconut);//叶子纹理
tex_treejointId=initTexture(r,R.raw.treetrunk);//树节点纹理
tex_waterId=initTexture(r,R.drawable.water);//水面纹理
tex_skyId=initTexture(r,R.drawable.sky);//天空纹理
}
}

View File

@@ -0,0 +1,176 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.opengl.GLES20;
import static com.bn.Sample13_3.Constant.*;
/*
* 灰度图生成地形
*/
public class LandForm
{
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maTexCoorHandle; //顶点纹理坐标属性引用
String mVertexShader;//顶点着色器
String mFragmentShader;//片元着色器
int uSandTexHandle;//土层纹理属性引用
int uGrassTexHandle;//草地纹理属性引用
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mTexCoorBuffer;//顶点纹理坐标数据缓冲
int vCount=0;
public LandForm(float[][]landArray,int mProgram)
{
this.mProgram=mProgram;
//初始化顶点坐标与着色数据
initVertexData(landArray);
//初始化shader
intShader();
}
//初始化顶点坐标与着色数据的方法
public void initVertexData(float[][] landArray)
{
int cols=landArray[0].length-1;//该灰度图的列数
int rows=landArray.length-1;//该灰度图的行数
vCount=cols*rows*2*3;//每个格子两个三角形每个三角形3个顶点
float vertices[]=new float[vCount*3];//每个顶点xyz三个坐标
int count=0;//顶点计数器
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
//计算当前格子左上侧点坐标
float zsx=j*LAND_SPAN;
float zsz=i*LAND_SPAN;
//绘制左上三角形
//左上点
vertices[count++]=zsx;
vertices[count++]=landArray[i][j];
vertices[count++]=zsz;
//左下点
vertices[count++]=zsx;
vertices[count++]=landArray[i+1][j];
vertices[count++]=zsz+LAND_SPAN;
//右上点
vertices[count++]=zsx+LAND_SPAN;
vertices[count++]=landArray[i][j+1];
vertices[count++]=zsz;
//右上点
vertices[count++]=zsx+LAND_SPAN;
vertices[count++]=landArray[i][j+1];
vertices[count++]=zsz;
//左下点
vertices[count++]=zsx;
vertices[count++]=landArray[i+1][j];
vertices[count++]=zsz+LAND_SPAN;
//右下点
vertices[count++]=zsx+LAND_SPAN;
vertices[count++]=landArray[i+1][j+1];
vertices[count++]=zsz+LAND_SPAN;
}
}
//创建顶点坐标数据缓冲
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为Float型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
float[] texCoor=generateTexCoor(cols,rows);
//创建顶点纹理坐标数据缓冲
ByteBuffer cbb = ByteBuffer.allocateDirect(texCoor.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mTexCoorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mTexCoorBuffer.put(texCoor);//向缓冲区中放入顶点着色数据
mTexCoorBuffer.position(0);//设置缓冲区起始位置
}
//初始化shader
public void intShader()
{
//获取程序中顶点位置属性引用
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点纹理坐标属性引用
maTexCoorHandle= GLES20.glGetAttribLocation(mProgram, "aTexCoor");
//获取程序中总变换矩阵引用
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//纹理id
uSandTexHandle=GLES20.glGetUniformLocation(mProgram, "sTextureSand");
uGrassTexHandle=GLES20.glGetUniformLocation(mProgram, "sTextureGrass");
}
public void drawSelf(int tex_grassId,int tex_sandId)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将顶点位置数据传入渲染管线
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//将顶点纹理坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//启用顶点位置、纹理坐标数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex_sandId);
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex_grassId);
GLES20.glUniform1i(uSandTexHandle, 0);
GLES20.glUniform1i(uGrassTexHandle, 1);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES , 0, vCount);
}
//自动切分纹理产生纹理数组的方法
public float[] generateTexCoor(int bw,int bh)
{
float[] result=new float[bw*bh*6*2];
float sizew=8.0f/bw;//列数
float sizeh=8.0f/bh;//行数
int c=0;
for(int i=0;i<bh;i++)
{
for(int j=0;j<bw;j++)
{
//每行列一个矩形由两个三角形构成共六个点12个纹理坐标
float s=j*sizew;
float t=i*sizeh;
result[c++]=s;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t+sizeh;
}
}
return result;
}
}

View File

@@ -0,0 +1,138 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.*;
import android.opengl.Matrix;
//存储系统矩阵状态的类
public class MatrixState
{
static float[] mProjMatrix = new float[16];//4x4矩阵 投影用
static float[] mVMatrix = new float[16];//摄像机位置朝向9参数矩阵
private static float[] currMatrix;//当前变换矩阵
public static FloatBuffer cameraFB;
public static float[] lightLocation=new float[]{0,0,0};//定位光光源位置
public static FloatBuffer lightPositionFB;//燈光的位置
public static Stack<float[]> mStack=new Stack<float[]>();//保护变换矩阵的栈
public static void setInitStack()//获取不变换初始矩阵
{
currMatrix=new float[16];
Matrix.setRotateM(currMatrix, 0, 0, 1, 0, 0);
}
public static void pushMatrix()//保护变换矩阵
{
mStack.push(currMatrix.clone());
}
public static void popMatrix()//恢复变换矩阵
{
currMatrix=mStack.pop();
}
public static void translate(float x,float y,float z)//设置沿xyz轴移动
{
Matrix.translateM(currMatrix, 0, x, y, z);
}
public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴移动
{
Matrix.rotateM(currMatrix,0,angle,x,y,z);
}
//设置摄像机
public static void setCamera
(
float cx, //摄像机位置x
float cy, //摄像机位置y
float cz, //摄像机位置z
float tx, //摄像机目标点x
float ty, //摄像机目标点y
float tz, //摄像机目标点z
float upx, //摄像机UP向量X分量
float upy, //摄像机UP向量Y分量
float upz //摄像机UP向量Z分量
)
{
Matrix.setLookAtM
(
mVMatrix,
0,
cx,
cy,
cz,
tx,
ty,
tz,
upx,
upy,
upz
);
float[] cameraLocation=new float[3];//摄像机位置
cameraLocation[0]=cx;
cameraLocation[1]=cy;
cameraLocation[2]=cz;
ByteBuffer llbb = ByteBuffer.allocateDirect(3*4);
llbb.order(ByteOrder.nativeOrder());//设置字节顺序
cameraFB=llbb.asFloatBuffer();
cameraFB.put(cameraLocation);
cameraFB.position(0);
}
//设置透视投影参数
public static void setProjectFrustum
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//设置正交投影参数
public static void setProjectOrtho
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.orthoM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//获取具体物体的总变换矩阵
public static float[] getFinalMatrix()
{
float[] mMVPMatrix=new float[16];
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, currMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
return mMVPMatrix;
}
//获取具体物体的变换矩阵
public static float[] getMMatrix()
{
return currMatrix;
}
//设置灯光位置的方法
public static void setLightLocation(float x,float y,float z)
{
lightLocation[0]=x;
lightLocation[1]=y;
lightLocation[2]=z;
ByteBuffer llbb = ByteBuffer.allocateDirect(3*4);
llbb.order(ByteOrder.nativeOrder());//设置字节顺序
lightPositionFB=llbb.asFloatBuffer();
lightPositionFB.put(lightLocation);
lightPositionFB.position(0);
}
}

View File

@@ -0,0 +1,235 @@
package com.bn.Sample13_3;
import static com.bn.Sample13_3.Constant.SCREEN_HEIGHT;
import static com.bn.Sample13_3.Constant.SCREEN_WIDTH;
import static com.bn.Sample13_3.Constant.flag_go;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class Sample13_3_Activity extends Activity
{
private GameSurfaceView mGLSurfaceView;
AudioManager mgr;// 音频管理者
SoundPool soundPool;// 声音池
MediaPlayer bgMusic;// 游戏背景音乐播放器
HashMap<Integer,Integer> soundMap;//存放声音池中的声音ID的Map
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
initScreen();
initSound();//在activity中的onCreate方法中调用
//初始化GLSurfaceView
mGLSurfaceView = new GameSurfaceView(this);
setContentView(mGLSurfaceView);
mGLSurfaceView.requestFocus();//获取焦点
mGLSurfaceView.setFocusableInTouchMode(true);//设置为可触控
bgMusic.start();
}
//初始化屏幕
public void initScreen()
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//设置为横屏模式
SCREEN_WIDTH=getWindowManager().getDefaultDisplay().getWidth();
SCREEN_HEIGHT=getWindowManager().getDefaultDisplay().getHeight();
}
@Override
protected void onResume()
{
super.onResume();
mGLSurfaceView.onResume();
flag_go=true;
}
@Override
protected void onPause()
{
super.onPause();
mGLSurfaceView.onPause();
flag_go=false;
}
//创建选项菜单
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "风向")
.setIcon(R.drawable.icon);
menu.add(0, 1, 0, "风力")
.setIcon(R.drawable.icon);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case 0:
showDialog(0);
break;
case 1:
showDialog(1);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public Dialog onCreateDialog(int id)
{
Dialog dialog=null;
switch(id)
{
case 0://生成普通对话框的代码
String msg="当前的风向为: "+Constant.wind_direction+"";
LayoutInflater factory = LayoutInflater.from(this);
View view = factory.inflate(R.layout.seekbar, null);
final TextView tv=(TextView)view.findViewById(R.id.seekbar_tv);
tv.setText(msg);
final SeekBar sb=(SeekBar)view.findViewById(R.id.seekbar_sb);
sb.setMax(359);
sb.setProgress((int)Constant.wind_direction);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser)
{
Constant.wind_direction=sb.getProgress();
tv.setText("当前的风向为: "+(float)sb.getProgress()+"");
}
});
Builder b=new AlertDialog.Builder(this);
b.setIcon(R.drawable.icon);//设置图标
b.setTitle("设置风向");//设置标题
b.setView(view);
b.setPositiveButton//为对话框设置按钮
(
"确定",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Constant.wind_direction=sb.getProgress();
}
}
);
dialog=b.create();
break;
case 1://生成普通对话框的代码
msg="当前的风力为: "+Constant.wind+"";
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.seekbar, null);
final TextView tv1=(TextView)view.findViewById(R.id.seekbar_tv);
tv1.setText(msg);
final SeekBar sb1=(SeekBar)view.findViewById(R.id.seekbar_sb);
sb1.setMax(12);
sb1.setProgress(Constant.wind);
sb1.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser)
{
Constant.setWindForce(sb1.getProgress());
tv1.setText("当前的风力为: "+sb1.getProgress()+"");
}
});
b=new AlertDialog.Builder(this);
b.setIcon(R.drawable.icon);//设置图标
b.setTitle("设置风力");//设置标题
b.setView(view);
b.setPositiveButton//为对话框设置按钮
(
"确定",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Constant.setWindForce(sb1.getProgress());
}
}
);
dialog=b.create();
break;
}
return dialog;
}
//加载声音资源
public void initSound()
{
// 获取音频管理者
mgr = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// 初始化媒体播放器
bgMusic = MediaPlayer.create(this, R.raw.gamebg_music);
bgMusic.setLooping(true);// 是否循环
// 初始化声音池
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 5);// 创建声音池
soundMap = new HashMap<Integer, Integer>();// 创建map
soundMap.put(0, soundPool.load(this, R.raw.wind, 1));
}
//播放声音池的方法
public void playSound(int sound,int loop)
{
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
soundPool.play
(
soundMap.get(sound), //声音资源id
volume, //左声道音量
volume, //右声道音量
1, //优先级
loop, //循环次数 -1带表永远循环
0.5f //回放速度0.5f2.0f之间
);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent e)
{
//控制音量键只能控制媒体音量的大小
if(keyCode==KeyEvent.KEYCODE_VOLUME_DOWN||keyCode==KeyEvent.KEYCODE_VOLUME_UP)
{
setVolumeControlStream(AudioManager.STREAM_MUSIC);
return super.onKeyDown(keyCode, e);
}
if(keyCode==4)
{
System.exit(0);
return true;
}
return super.onKeyDown(keyCode, e);
}
}

View File

@@ -0,0 +1,198 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import static com.bn.Sample13_3.Constant.*;
import android.opengl.GLES20;
/*
* 绘制海水
* 能够进行波动
*/
public class SeaWater
{
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maTexCoorHandle; //顶点纹理坐标属性引用
int maStartAngleHandle; //本帧起始角度属性引用\
int muWidthSpanHandle;//横向长度总跨度引用
int currIndex=0;//当前着色器索引
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mTexCoorBuffer;//顶点纹理坐标数据缓冲
int vCount=0;
float currStartAngle=0;//当前帧的起始角度0~2PI
float texSize=16;
public SeaWater(int mProgram)
{
this.mProgram=mProgram;
//初始化顶点坐标
initVertexData();
//着色数据
intShader();
//启动一个线程定时换帧
new Thread()
{
public void run()
{
while(flag_go)
{
currStartAngle+=(Math.PI/16);
try
{
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}.start();
}
public void initVertexData()
{
vCount=COLS*ROWS*2*3;//每个格子两个三角形每个三角形3个顶点
float vertices[]=new float[vCount*3];//每个顶点xyz三个坐标
int count=0;//顶点计数器
for(int i=0;i<ROWS;i++)//逐行扫描
{
for(int j=0;j<COLS;j++)//逐列扫描
{
//计算当前格子左上侧点坐标
float zsx=j*WATER_SPAN;
float zsy=0;
float zsz=i*WATER_SPAN;
//左上点
vertices[count++]=zsx;
vertices[count++]=zsy;
vertices[count++]=zsz;
//左下点
vertices[count++]=zsx;
vertices[count++]=zsy;
vertices[count++]=zsz+WATER_SPAN;
//右上点
vertices[count++]=zsx+WATER_SPAN;
vertices[count++]=zsy;
vertices[count++]=zsz;
//右上点
vertices[count++]=zsx+WATER_SPAN;
vertices[count++]=zsy;
vertices[count++]=zsz;
//左下点
vertices[count++]=zsx;
vertices[count++]=zsy;
vertices[count++]=zsz+WATER_SPAN;
//右下点
vertices[count++]=zsx+WATER_SPAN;
vertices[count++]=zsy;
vertices[count++]=zsz+WATER_SPAN;
}
}
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为Float型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
float texCoor[]=generateTexCoor(COLS,ROWS);
//创建顶点纹理坐标数据缓冲
ByteBuffer cbb = ByteBuffer.allocateDirect(texCoor.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mTexCoorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mTexCoorBuffer.put(texCoor);//向缓冲区中放入顶点着色数据
mTexCoorBuffer.position(0);//设置缓冲区起始位置
}
//初始化shader
public void intShader()
{
//获取程序中顶点位置属性引用
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点纹理坐标属性引用
maTexCoorHandle = GLES20.glGetAttribLocation(mProgram, "aTexCoor");
//获取程序中总变换矩阵引用
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//获取本帧起始角度属性引用
maStartAngleHandle =GLES20.glGetUniformLocation(mProgram, "uStartAngle");
//获取横向长度总跨度引用
muWidthSpanHandle =GLES20.glGetUniformLocation(mProgram, "uWidthSpan");
}
public void drawSelf(int texId)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将本帧起始角度传入shader程序
GLES20.glUniform1f(maStartAngleHandle, currStartAngle);
//将横向长度总跨度传入shader程序
GLES20.glUniform1f(muWidthSpanHandle, UNIT_SIZE*31*3);
//将顶点位置数据传入渲染管线
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//将顶点纹理坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//启用顶点位置、纹理坐标数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
//自动切分纹理产生纹理数组的方法
public float[] generateTexCoor(int bw,int bh)
{
float[] result=new float[bw*bh*6*2];
float sizew=texSize/bw;//列数
float sizeh=texSize/bh;//行数
int c=0;
for(int i=0;i<bh;i++)
{
for(int j=0;j<bw;j++)
{
//每行列一个矩形由两个三角形构成共六个点12个纹理坐标
float s=j*sizew;
float t=i*sizeh;
result[c++]=s;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t+sizeh;
}
}
return result;
}
}

View File

@@ -0,0 +1,64 @@
package com.bn.Sample13_3;
import android.content.res.Resources;
/*
* 该shader管理器主要是用于加载shader和编译shader
*/
public class ShaderManager
{
final static String[][] shaderName=
{
{"vertex_tree.sh","frag_tree.sh"},//椰子树的着色器
{"vertex_tex.sh","frag_tex.sh"},//纹理贴图的着色器
{"vertex_water.sh","frag_water.sh"},//海水的着色器
{"vertex_landform.sh","frag_landform.sh"},//山的着色器
{"vertex_leaves.sh","frag_leaves.sh"},//叶子的着色器
};
static String[]mVertexShader=new String[shaderName.length];//顶点着色器字符串数组
static String[]mFragmentShader=new String[shaderName.length];//片元着色器字符串数组
static int[] program=new int[shaderName.length];//程序数组
//加载shader字符串
public static void loadCodeFromFile(Resources r)
{
for(int i=0;i<shaderName.length;i++)
{
//加载顶点着色器的脚本内容
mVertexShader[i]=ShaderUtil.loadFromAssetsFile(shaderName[i][0],r);
//加载片元着色器的脚本内容
mFragmentShader[i]=ShaderUtil.loadFromAssetsFile(shaderName[i][1], r);
}
}
//编译shader
public static void compileShader()
{
for(int i=0;i<shaderName.length;i++)
{
program[i]=ShaderUtil.createProgram(mVertexShader[i], mFragmentShader[i]);
}
}
//这里返回的是椰子树摇动的shader程序
public static int getTreeWaveShaderProgram()
{
return program[0];
}
//这里返回的是纹理贴图的shader
public static int getTextureShaderProgram()
{
return program[1];
}
//这里返回的是海水的shader
public static int getWaterShaderProgram()
{
return program[2];
}
//这里返回山的颜色的shader
public static int getLandFormShaderProgram()
{
return program[3];
}
//这里返回叶子的颜色的shader
public static int getLeavesShaderProgram()
{
return program[4];
}
}

View File

@@ -0,0 +1,126 @@
package com.bn.Sample13_3;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.content.res.Resources;
import android.opengl.GLES20;
import android.util.Log;
//加载顶点Shader与片元Shader的工具类
public class ShaderUtil
{
//加载制定shader的方法
public static int loadShader
(
int shaderType, //shader的类型 GLES20.GL_VERTEX_SHADER GLES20.GL_FRAGMENT_SHADER
String source //shader的脚本字符串
)
{
//创建一个新shader
int shader = GLES20.glCreateShader(shaderType);
//若创建成功则加载shader
if (shader != 0)
{
//加载shader的源代码
GLES20.glShaderSource(shader, source);
//编译shader
GLES20.glCompileShader(shader);
//存放编译成功shader数量的数组
int[] compiled = new int[1];
//获取Shader的编译情况
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0)
{//若编译失败则显示错误日志并删除此shader
Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":");
Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
//创建shader程序的方法
public static int createProgram(String vertexSource, String fragmentSource)
{
//加载顶点着色器
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0)
{
return 0;
}
//加载片元着色器
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0)
{
return 0;
}
//创建程序
int program = GLES20.glCreateProgram();
//若程序创建成功则向程序中加入顶点着色器与片元着色器
if (program != 0)
{
//向程序中加入顶点着色器
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
//向程序中加入片元着色器
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
//链接程序
GLES20.glLinkProgram(program);
//存放链接成功program数量的数组
int[] linkStatus = new int[1];
//获取program的链接情况
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
//若链接失败则报错并删除程序
if (linkStatus[0] != GLES20.GL_TRUE)
{
Log.e("ES20_ERROR", "Could not link program: ");
Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
//检查每一步操作是否有错误的方法
public static void checkGlError(String op)
{
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR)
{
Log.e("ES20_ERROR", op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
//从sh脚本中加载shader内容的方法
public static String loadFromAssetsFile(String fname,Resources r)
{
String result=null;
try
{
InputStream in=r.getAssets().open(fname);
int ch=0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch=in.read())!=-1)
{
baos.write(ch);
}
byte[] buff=baos.toByteArray();
baos.close();
in.close();
result=new String(buff,"UTF-8");
result=result.replaceAll("\\r\\n","\n");
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,222 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import android.opengl.GLES20;
/*
* 绘制纹理天空球
*/
public class SkyBall
{
//自定义渲染管线着色器程序id
int mProgram;
//总变换矩阵的引用
int muMVPMatrixHandle;
//顶点属性的引用
int maPositionHandle;
//顶点纹理坐标属性的引用
int maTexCoorHandle;
//顶点数据缓冲以及顶点纹理坐标数据缓冲
FloatBuffer mVertexBuffer;
FloatBuffer mTexCoorBuffer;
//顶点数量
int vCount=0;
float startX;
float startY;
float startZ;
public SkyBall(float radius,int mProgram,float startX,float startY,float startZ)
{
this.mProgram=mProgram;
this.startX=startX;
this.startY=startY;
this.startZ=startZ;
initVertexData(radius,startX,startY,startZ);
initShader();
}
//初始化顶点数据的方法
public void initVertexData(float radius,float startX,float startY,float startZ)
{
float ANGLE_SPAN=18;//切分间隔
float angleV=90;//纵向上的起始度数
//获取切分整图的纹理数组
float[] texCoorArray=
generateTexCoor
(
(int)(360/ANGLE_SPAN), //纹理图切分的列数
(int)(angleV/ANGLE_SPAN) //纹理图切分的行数
);
int tc=0;//纹理数组计数器
int ts=texCoorArray.length;//纹理数组长度
ArrayList<Float> alVertix=new ArrayList<Float>();//存放顶点坐标的ArrayList
ArrayList<Float> alTexture=new ArrayList<Float>();//存放纹理坐标的ArrayList
for(float vAngle=angleV;vAngle>0;vAngle=vAngle-ANGLE_SPAN)//垂直方向angleSpan度一份
{
for(float hAngle=360;hAngle>0;hAngle=hAngle-ANGLE_SPAN)//水平方向angleSpan度一份
{
//纵向横向各到一个角度后计算对应的此点在球面上的四边形顶点坐标
//并构建两个组成四边形的三角形
double xozLength=radius*Math.cos(Math.toRadians(vAngle));
float x1=(float)(xozLength*Math.cos(Math.toRadians(hAngle)));
float z1=(float)(xozLength*Math.sin(Math.toRadians(hAngle)));
float y1=(float)(radius*Math.sin(Math.toRadians(vAngle)));
xozLength=radius*Math.cos(Math.toRadians(vAngle-ANGLE_SPAN));
float x2=(float)(xozLength*Math.cos(Math.toRadians(hAngle)));
float z2=(float)(xozLength*Math.sin(Math.toRadians(hAngle)));
float y2=(float)(radius*Math.sin(Math.toRadians(vAngle-ANGLE_SPAN)));
xozLength=radius*Math.cos(Math.toRadians(vAngle-ANGLE_SPAN));
float x3=(float)(xozLength*Math.cos(Math.toRadians(hAngle-ANGLE_SPAN)));
float z3=(float)(xozLength*Math.sin(Math.toRadians(hAngle-ANGLE_SPAN)));
float y3=(float)(radius*Math.sin(Math.toRadians(vAngle-ANGLE_SPAN)));
xozLength=radius*Math.cos(Math.toRadians(vAngle));
float x4=(float)(xozLength*Math.cos(Math.toRadians(hAngle-ANGLE_SPAN)));
float z4=(float)(xozLength*Math.sin(Math.toRadians(hAngle-ANGLE_SPAN)));
float y4=(float)(radius*Math.sin(Math.toRadians(vAngle)));
//构建第一三角形
alVertix.add(x1);alVertix.add(y1);alVertix.add(z1);
alVertix.add(x4);alVertix.add(y4);alVertix.add(z4);
alVertix.add(x2);alVertix.add(y2);alVertix.add(z2);
//构建第二三角形
alVertix.add(x2);alVertix.add(y2);alVertix.add(z2);
alVertix.add(x4);alVertix.add(y4);alVertix.add(z4);
alVertix.add(x3);alVertix.add(y3);alVertix.add(z3);
//第一三角形3个顶点的6个纹理坐标
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
//第二三角形3个顶点的6个纹理坐标
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
alTexture.add(texCoorArray[tc++%ts]);
}
}
vCount=alVertix.size()/3;//顶点的数量为坐标值数量的1/3因为一个顶点有3个坐标
//将alVertix中的坐标值转存到一个float数组中
float vertices[]=new float[vCount*3];
for(int i=0;i<alVertix.size();i++)
{
vertices[i]=alVertix.get(i);
}
//创建绘制顶点数据缓冲
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为float型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//创建纹理坐标缓冲
float textureCoors[]=new float[alTexture.size()];//顶点纹理值数组
for(int i=0;i<alTexture.size();i++)
{
textureCoors[i]=alTexture.get(i);
}
ByteBuffer tbb = ByteBuffer.allocateDirect(textureCoors.length*4);
tbb.order(ByteOrder.nativeOrder());//设置字节顺序
mTexCoorBuffer = tbb.asFloatBuffer();//转换为int型缓冲
mTexCoorBuffer.put(textureCoors);//向缓冲区中放入顶点着色数据
mTexCoorBuffer.position(0);//设置缓冲区起始位置
}
//初始化Shader程序的方法
public void initShader()
{
//获得顶点坐标数据的引用
maPositionHandle=GLES20.glGetAttribLocation(mProgram, "aPosition");
//顶点纹理坐标的引用
maTexCoorHandle=GLES20.glGetAttribLocation(mProgram, "aTexCoor");
muMVPMatrixHandle=GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
}
public void drawSelf(int texId,float rotationAngle_Y)
{
MatrixState.pushMatrix();
MatrixState.translate(startX, startY, startZ);
MatrixState.rotate(rotationAngle_Y, 0, 1, 0);
//使用某套指定的Shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入到Shader程序中
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//将纹理坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//启用顶点位置数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
MatrixState.popMatrix();
}
//自动切分纹理产生纹理数组的方法
public float[] generateTexCoor(int bw,int bh)
{
float[] result=new float[bw*bh*6*2];
float sizew=1.0f/bw;//列数
float sizeh=1.0f/bh;//行数
int c=0;
for(int i=0;i<bh;i++)
{
for(int j=0;j<bw;j++)
{
//每行列一个矩形由两个三角形构成共六个点12个纹理坐标
float s=j*sizew;
float t=i*sizeh;
result[c++]=s;
result[c++]=t;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s+sizew;
result[c++]=t+sizeh;
}
}
return result;
}
}

View File

@@ -0,0 +1,232 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.opengl.GLES20;
/*
* 用于绘制树叶矩形
*/
public class TreeLeaves
{
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maTexCoorHandle; //顶点纹理坐标属性引用
String mVertexShader;//顶点着色器
String mFragmentShader;//片元着色器
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mTexCoorBuffer;//顶点纹理坐标数据缓冲
int vCount=0;
float centerX;//树叶中心点X坐标
float centerZ;//树叶中心点Z坐标
int index;//当前树的索引
public TreeLeaves(int mProgram,float width,float height,float absolute_height,int index)
{
this.mProgram=mProgram;
//初始化顶点坐标与着色数据
initVertexData(width,height,absolute_height,index);
//初始化shader
intShader();
this.index=index;
}
//初始化顶点坐标与着色数据的方法
public void initVertexData(float width,float height,float absolute_height,int index)
{
vCount=6;
float vertices[]=null;//顶点坐标
float texCoor[]=null;//纹理坐标
switch(index)//自动生成每片树叶
{
case 0://平行于X轴正方向开始,逆时针旋转,每个60度,增加一片树叶
vertices=new float[]
{
0,height+absolute_height,0,
0,absolute_height,0,
width,height+absolute_height,0,
width,height+absolute_height,0,
0,absolute_height,0,
width,absolute_height,0,
};
texCoor=new float[]
{
1,0, 1,1, 0,0,
0,0, 1,1, 0,1
};
//确定中心点坐标
centerX=width/2;
centerZ=0;
break;
case 1://60度角的树叶
vertices=new float[]
{
0,height+absolute_height,0,
0,absolute_height,0,
width/2,height+absolute_height,(float) (-width*Math.sin(Math.PI/3)),
width/2,height+absolute_height,(float) (-width*Math.sin(Math.PI/3)),
0,absolute_height,0,
width/2,absolute_height,(float) (-width*Math.sin(Math.PI/3))
};
texCoor=new float[]
{
1,0, 1,1, 0,0,
0,0, 1,1, 0,1
};
//确定中心点坐标
centerX=width/4;
centerZ=(float) (-width*Math.sin(Math.PI/3))/2;
break;
case 2:
vertices=new float[]
{
-width/2,height+absolute_height,(float) (-width*Math.sin(Math.PI/3)),
-width/2,absolute_height,(float) (-width*Math.sin(Math.PI/3)),
0,height+absolute_height,0,
0,height+absolute_height,0,
-width/2,absolute_height,(float) (-width*Math.sin(Math.PI/3)),
0,absolute_height,0,
};
texCoor=new float[]
{
0,0, 0,1, 1,0,
1,0, 0,1, 1,1
};
//确定中心点坐标
centerX=-width/4;
centerZ=(float) (-width*Math.sin(Math.PI/3))/2;
break;
case 3:
vertices=new float[]
{
-width,height+absolute_height,0,
-width,absolute_height,0,
0,height+absolute_height,0,
0,height+absolute_height,0,
-width,absolute_height,0,
0,absolute_height,0,
};
texCoor=new float[]
{
0,0, 0,1, 1,0,
1,0, 0,1, 1,1
};
//确定中心点坐标
centerX=-width/2;
centerZ=0;
break;
case 4:
vertices=new float[]
{
-width/2,height+absolute_height,(float) (width*Math.sin(Math.PI/3)),
-width/2,absolute_height,(float) (width*Math.sin(Math.PI/3)),
0,height+absolute_height,0,
0,height+absolute_height,0,
-width/2,absolute_height,(float) (width*Math.sin(Math.PI/3)),
0,absolute_height,0,
};
texCoor=new float[]
{
0,0, 0,1, 1,0,
1,0, 0,1, 1,1
};
//确定中心点坐标
centerX=-width/4;
centerZ=(float) (width*Math.sin(Math.PI/3))/2;
break;
case 5:
vertices=new float[]
{
0,height+absolute_height,0,
0,absolute_height,0,
width/2,height+absolute_height,(float) (width*Math.sin(Math.PI/3)),
width/2,height+absolute_height,(float) (width*Math.sin(Math.PI/3)),
0,absolute_height,0,
width/2,absolute_height,(float) (width*Math.sin(Math.PI/3))
};
texCoor=new float[]
{
1,0, 1,1, 0,0,
0,0, 1,1, 0,1
};
//确定中心点坐标
centerX=width/4;
centerZ=(float) (width*Math.sin(Math.PI/3))/2;
break;
}
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为Float型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//特别提示由于不同平台字节顺序不同数据单元不是字节的一定要经过ByteBuffer
//转换关键是要通过ByteOrder设置nativeOrder(),否则有可能会出问题
//顶点坐标数据的初始化================end============================
//顶点纹理坐标数据的初始化================begin============================
//创建顶点纹理坐标数据缓冲
ByteBuffer cbb = ByteBuffer.allocateDirect(texCoor.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mTexCoorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mTexCoorBuffer.put(texCoor);//向缓冲区中放入顶点着色数据
mTexCoorBuffer.position(0);//设置缓冲区起始位置
}
//初始化shader
public void intShader()
{
//获取程序中顶点位置属性引用
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点纹理坐标属性引用
maTexCoorHandle= GLES20.glGetAttribLocation(mProgram, "aTexCoor");
//获取程序中总变换矩阵引用
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
}
public void drawSelf(int texId)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将顶点位置数据传入渲染管线
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//将顶点纹理坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//启用顶点位置、纹理坐标数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
}

View File

@@ -0,0 +1,76 @@
package com.bn.Sample13_3;
/*
* 叶子的控制类
*/
public class TreeLeavesControl implements Comparable<TreeLeavesControl>
{
//叶子的位置
float positionX;
float positionY;
float positionZ;
//叶子
TreeLeaves treeLeaves;
public TreeLeavesControl(float positionX,float positionY,float positionZ,TreeLeaves treeLeaves)
{
this.positionX=positionX;
this.positionY=positionY;
this.positionZ=positionZ;
this.treeLeaves=treeLeaves;
}
public void drawSelf(int tex_leavesId,float bend_R,float wind_direction)
{
MatrixState.pushMatrix();
MatrixState.translate(positionX, positionY, positionZ);
//在这里需要计算叶子相对于树干来说的偏移位置和旋转方向
//---------------------------
float curr_height=Constant.leaves_absolute_height;
//树干最高点的位置
float result[]=resultPoint(wind_direction,bend_R,0,curr_height,0);
//需要的旋转轴
//需要旋转的角度
MatrixState.translate(result[0], result[1], result[2]);
MatrixState.rotate(result[5], result[3],0,-result[4]);
//---------------------------------
treeLeaves.drawSelf(tex_leavesId);
MatrixState.popMatrix();
}
//这里对每片树叶距离摄像机的远近距离进行 排序, 从大到小排序
@Override
public int compareTo(TreeLeavesControl another)
{
//当前树叶距离摄像机的距离
float distanceX=(this.positionX+this.treeLeaves.centerX-GameSurfaceView.cx)*(this.positionX+this.treeLeaves.centerX-GameSurfaceView.cx);
float distanceZ=(this.positionZ+this.treeLeaves.centerZ-GameSurfaceView.cz)*(this.positionZ+this.treeLeaves.centerZ-GameSurfaceView.cz);
//比较点距离摄像机的距离
float distanceOX=(another.positionX+another.treeLeaves.centerX-GameSurfaceView.cx)*(another.positionX+another.treeLeaves.centerX-GameSurfaceView.cx);
float distanceOZ=(another.positionZ+another.treeLeaves.centerZ-GameSurfaceView.cz)*(another.positionZ+another.treeLeaves.centerZ-GameSurfaceView.cz);
return (distanceX+distanceZ)>(distanceOX+distanceOZ)?-1:1;
}
//生成最后顶点的位置
public float[] resultPoint(float direction_degree,float currBend_R,float pointX,float pointY,float pointZ)//currBend_R代表当前的风向,pointHeight当前点的高度
{
float []position=new float[6];
//计算当前的弧度
float curr_radian=pointY/currBend_R;
//计算当前点的结果高度
float result_Y=(float) (currBend_R*Math.sin(curr_radian));
//计算当前点的增加的长度
float increase=(float) (currBend_R-currBend_R*Math.cos(curr_radian));
//计算当前点最后的x坐标
float result_X=(float) (pointX+increase*Math.sin(Math.toRadians(direction_degree)));
//计算当前点最后的z坐标
float result_Z=(float) (pointZ+increase*Math.cos(Math.toRadians(direction_degree)));
//最后结果
position[0]=result_X;
position[1]=result_Y;
position[2]=result_Z;
//x向旋转轴
position[3]=(float) Math.cos(Math.toRadians(direction_degree));
//z向旋转轴
position[4]=(float) Math.sin(Math.toRadians(direction_degree));
//旋转角度
position[5]= (float) Math.toDegrees(curr_radian);
return position;
}
}

View File

@@ -0,0 +1,220 @@
package com.bn.Sample13_3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import android.opengl.GLES20;
/*
* 用于绘制树干
*/
public class TreeTrunk
{
//----------这里对树干的节点进行扭曲---------------------
int fBendRHandle;//创建弯曲半径的句柄Id
int fwind_direction_Handle;//风向角度的句柄
//--------------------------------------------
//自定义渲染管线着色器程序id
int mProgram;
//总变化矩阵引用的id
int muMVPMatrixHandle;
//顶点位置属性引用
int maPositionHandle;
//顶点纹理坐标属性引用
int maTexCoorHandle;
//顶点数据缓冲和纹理坐标数据缓冲顶点法向量数据缓冲
FloatBuffer mVertexBuffer;
FloatBuffer mTexCoorBuffer;
//顶点数量
int vCount=0;
//经度切分的角度
float longitude_span=12;
//构造器 树的第一个节点底端半径,第一个节点的顶端半径,每个节点的高度,节点的数量
public TreeTrunk(int mProgram,float bottom_Radius,float joint_Height,int jointNum,int availableNum)
{
this.mProgram=mProgram;
initVertexData(bottom_Radius,joint_Height,jointNum,availableNum);
initShader();
}
//初始化顶点数据的方法
public void initVertexData(float bottom_radius,float joint_Height,int jointNum,int availableNum)//R代表底端半径r代表顶端半径
{
List<Float> vertex_List=new ArrayList<Float>();//顶点坐标的集合
List<float[]> texture_List=new ArrayList<float[]>();//纹理坐标的集合
for(int num=0;num<availableNum;num++)//生成每个节点的顶点数据
{
//每个节点底端半径
float temp_bottom_radius=bottom_radius*(jointNum-num)/(float)jointNum;
//每个节点顶端半径
float temp_top_radius=bottom_radius*(jointNum-(num+1))/(float)jointNum;
//每个节点的底端高度
float temp_bottom_height=num*joint_Height;
//每个节点的顶端高度
float temp_top_height=(num+1)*joint_Height;
for(float hAngle=0;hAngle<360;hAngle=hAngle+longitude_span)//每个节点生成三角形数据
{
//左上点
float x0=(float) (temp_top_radius*Math.cos(Math.toRadians(hAngle)));
float y0=temp_top_height;
float z0=(float) (temp_top_radius*Math.sin(Math.toRadians(hAngle)));
//左下点
float x1=(float) (temp_bottom_radius*Math.cos(Math.toRadians(hAngle)));
float y1=temp_bottom_height;
float z1=(float) (temp_bottom_radius*Math.sin(Math.toRadians(hAngle)));
//右上点
float x2=(float) (temp_top_radius*Math.cos(Math.toRadians(hAngle+longitude_span)));
float y2=temp_top_height;
float z2=(float) (temp_top_radius*Math.sin(Math.toRadians(hAngle+longitude_span)));
//右下点
float x3=(float) (temp_bottom_radius*Math.cos(Math.toRadians(hAngle+longitude_span)));
float y3=temp_bottom_height;
float z3=(float) (temp_bottom_radius*Math.sin(Math.toRadians(hAngle+longitude_span)));
vertex_List.add(x0);vertex_List.add(y0);vertex_List.add(z0);
vertex_List.add(x1);vertex_List.add(y1);vertex_List.add(z1);
vertex_List.add(x2);vertex_List.add(y2);vertex_List.add(z2);
vertex_List.add(x2);vertex_List.add(y2);vertex_List.add(z2);
vertex_List.add(x1);vertex_List.add(y1);vertex_List.add(z1);
vertex_List.add(x3);vertex_List.add(y3);vertex_List.add(z3);
}
//创建纹理数据
//创建纹理坐标缓冲
float[] texcoor=generateTexCoor//获取切分整图的纹理数组
(
(int)(360/longitude_span), //纹理图切分的列数
1 //(int)(180/ANGLE_SPAN) //纹理图切分的行数
);
texture_List.add(texcoor);
}
//创建顶点缓冲
float[] vertex=new float[vertex_List.size()];
for(int i=0;i<vertex_List.size();i++)
{
vertex[i]=vertex_List.get(i);
}
vCount=vertex_List.size()/3;
ByteBuffer vbb=ByteBuffer.allocateDirect(vertex.length*4);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer=vbb.asFloatBuffer();
mVertexBuffer.put(vertex);
mVertexBuffer.position(0);
//创建纹理坐标缓冲
ArrayList<Float> al_temp=new ArrayList<Float>();
for(float []temp:texture_List)
{
for(float tem:temp)
{
al_temp.add(tem);
}
}
float[]texcoor=new float[al_temp.size()];
int num=0;
for(float temp:al_temp)
{
texcoor[num]=temp;
num++;
}
ByteBuffer tbb=ByteBuffer.allocateDirect(texcoor.length*4);
tbb.order(ByteOrder.nativeOrder());
mTexCoorBuffer=tbb.asFloatBuffer();
mTexCoorBuffer.put(texcoor);
mTexCoorBuffer.position(0);
}
//初始化Shader的方法
public void initShader()
{
//------------------------------摆动处理方法-----------------------
//获取程序中顶点位置属性引用
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点纹理坐标属性引用
maTexCoorHandle= GLES20.glGetAttribLocation(mProgram, "aTexCoor");
//获取程序中总变换矩阵引用
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//获取程序中树干弯曲半径的引用
fBendRHandle = GLES20.glGetUniformLocation(mProgram,"bend_R");
//获取程序中方向的角度引用
fwind_direction_Handle = GLES20.glGetUniformLocation(mProgram,"direction_degree");
}
//自定义的绘制方法drawSelf
public void drawSelf(int texId,float bend_R,float wind_direction)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将弯曲半径传入shader程序
GLES20.glUniform1f(fBendRHandle, bend_R);
//将风向传入shader程序
GLES20.glUniform1f(fwind_direction_Handle, wind_direction);
//将顶点位置数据传入渲染管线
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//将纹理坐标数据传入渲染管线
GLES20.glVertexAttribPointer
(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//启用顶点位置数据
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
//自动切分纹理产生纹理数组的方法
public float[] generateTexCoor(int bw,int bh)
{
float[] result=new float[bw*bh*6*2];
float sizew=1.0f/bw;//列数
float sizeh=1.0f/bh;//行数
int c=0;
for(int i=0;i<bh;i++)
{
for(int j=0;j<bw;j++)
{
//每行列一个矩形由两个三角形构成共六个点12个纹理坐标
float s=j*sizew;
float t=i*sizeh;
result[c++]=s;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s+sizew;
result[c++]=t;
result[c++]=s;
result[c++]=t+sizeh;
result[c++]=s+sizew;
result[c++]=t+sizeh;
}
}
return result;
}
}

View File

@@ -0,0 +1,29 @@
package com.bn.Sample13_3;
//该类为树干的控制类
public class TreeTrunkControl
{
static int num=0;
//标志
int flag=0;
//树的位置
float positionX;
float positionY;
float positionZ;
//树干的模型
TreeTrunk treeTrunk;
public TreeTrunkControl(float positionX,float positionY,float positionZ,TreeTrunk treeTrunk)
{
flag=num++;
this.positionX=positionX;
this.positionY=positionY;
this.positionZ=positionZ;
this.treeTrunk=treeTrunk;
}
public void drawSelf(int tex_treejointId,float bend_R,float wind_direction)
{
MatrixState.pushMatrix();
MatrixState.translate(positionX, positionY, positionZ);//移动到指定的位置
treeTrunk.drawSelf(tex_treejointId, bend_R, wind_direction);
MatrixState.popMatrix();
}
}

View File

@@ -0,0 +1,54 @@
package com.bn.Sample13_3;
import java.util.ArrayList;
import java.util.Collections;
import android.opengl.GLES20;
import static com.bn.Sample13_3.Constant.*;
//表示树的控制类,用于控制所有的树
public class TreesForControl
{
float height;
//存储所有树的列表
ArrayList<TreeTrunkControl> treeTrunkList=new ArrayList<TreeTrunkControl>();
ArrayList<TreeLeavesControl> treeLeavesList=new ArrayList<TreeLeavesControl>();
public TreesForControl(TreeTrunk treeTrunk,TreeLeaves[] treeLeaves)
{
//扫描地图生成各个位置的椰子树
for(int i=0;i<MAP_TREE.length;i++)
{
//创建所有的树干
treeTrunkList.add(new TreeTrunkControl(MAP_TREE[i][0],MAP_TREE[i][1],MAP_TREE[i][2],treeTrunk));
//创建所有的树叶
for(TreeLeaves tempLeaves:treeLeaves)
{
treeLeavesList.add(new TreeLeavesControl(MAP_TREE[i][0],MAP_TREE[i][1],MAP_TREE[i][2],tempLeaves));
}
}
}
//绘制列表中的每一颗树
public void drawSelf(int tex_leavesId,int tex_treejointId,float bend_R,float wind_direction)
{
//绘制树干
for(TreeTrunkControl tempTrunk:treeTrunkList)
{
tempTrunk.drawSelf(tex_treejointId, bend_R, wind_direction);
}
//对所有的叶子进行排序
Collections.sort(treeLeavesList);
//开启混合
GLES20.glEnable(GLES20.GL_BLEND);
//设置混合因子
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
//关闭背面剪裁
GLES20.glDisable(GLES20.GL_CULL_FACE);
//绘制所有的叶子
for(TreeLeavesControl tempLeaves:treeLeavesList)
{
tempLeaves.drawSelf(tex_leavesId,bend_R,wind_direction);
}
//打开背面剪裁
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_BLEND);
}
}